簡體   English   中英

與給定方法簽名不兼容的泛型類型?

[英]Generic Types incompatible with given method signature?

給出以下方法:

public <E> void bindContentBidirectional(final String fieldPath,
        final String itemFieldPath, final Class<?> itemFieldPathType,
        final ObservableList<E> list, final Class<E> listValueType,
        final SelectionModel<E> selectionModel,
        final String selectionModelItemMasterPath)

我是否理解正確,如果我將ObservableList<PrintablePredicate<SomeClass>>作為其類型:

final ObservableList<E> list

(即E = PrintablePredicate<SomeClass> ,由於下一個參數,它永遠無法工作:

final Class<E> listValueType) 

我只能寫PrintablePredicate.class,而不能寫PrintablePredicate.class,因為泛型類型沒有得到驗證。 換句話說,bindContentBidirectional的給定方法簽名與所有E不兼容,因此E具有泛型類型參數。

將它們放到一個具體的代碼場景中,說我們有:

@FXML private CheckListView<PrintablePredicate<Miner>> profileConditions;      
private MinerMonitorProfile minerMonitorProfile;

private void initialize() {
    BeanPathAdapter<MinerMonitorProfile> minerMonitorProfileBPA = new BeanPathAdapter<>    (this.minerMonitorProfile);
    minerMonitorProfileBPA.bindContentBidirectional("conditions", null, String.class, this.profileConditions.getItems(), PrintablePredicate.class, null, null);
}

編譯器說:

BeanPathAdapter<MinerMonitorProfile>類型的方法bindContentBidirectional(String, String, Class<?>, ObservableList<E>, Class<E>, SelectionModel<E>, String)不適用於參數( StringnullClass<String>ObservableList<PrintablePredicate<Miner>>Class<PrintablePredicate>nullnull

有沒有辦法解決? 謝謝!

注意: this.profileConditions.getItems()返回類型: ObservableList<PrintablePredicate<Miner>>

還要注意,參數化方法調用的方式如下:

minerMonitorProfileBPA.<PrintablePredicate<Miner>>bindContentBidirectional("conditions", null, String.class, this.profileConditions.getItems(), PrintablePredicate.class, null, null);

不能緩解問題。

當我遇到此類問題(將普通類投射到參數化類嗎?)時,我會使用雙重強制轉換,以繞過編譯器抱怨。

所以我想你可以寫

(Class<PrintablePredicate<Miner>>)(Class<?>) PrintablePredicate.class

PrintablePredicate.class參數傳遞給bindContentBidirectional函數時。


編輯:我發現只是將PrintablePredicate.class強制轉換為Class(我不明白為什么會這樣,因為* .class已經是Class類型,所以我認為這似乎是不必要的)或在將其傳遞給變量之前將其分配給變量方法適用於這種情況(使用javac 1.8.0_25)。 因此,也許您應該只使用它而不是上面的代碼:

(Class)PrintablePredicate.class

因此,您的錯誤可能是由於類似於OpenJDK的編譯器錯誤引起的(是的,因為它是一個錯誤,所以沒有任何意義): https : //bugs.openjdk.java.net/browse/JDK-8028682


作為總結,然后根據我的發現,這種“雙重轉換”技巧(或只是將一個對象分配給變量)可以幫助您“輕松”使編譯器在有此類錯誤時“理解”您的代碼一個似乎(大笑,我猜這很有趣,但這只是向您表明有時候您甚至不能信任編譯器)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM