盡管我目前有一個用例,其中我有一個泛型類型,但我還沒有找到它,它有一個 methodfoo(int)和一個 method foo(T)。對于我的用例,所說的類型是用 T = Integer 實例化的,這意味著我有方法foo(int)和foo(Integer). 每當我嘗試調用foo(Integer)它時foo(int),無論是否指定類型,無論我是否強制轉換。解決它的唯一方法是使用 Long 代替,我不想這樣做。有什么辦法可以強制java使用該foo(Integer)方法嗎?編輯:有一次,為了回答評論,我認為代碼在這里不相關,因為我所描述的內容足以理解我的意思。其次,錯誤是在我的最后,我道歉。我沒有預期的行為,并認為這是因為這方面的問題,特別是因為我的 IDE 顯示了該foo(int)方法的用法。我現在要關閉這個一個 MVCE:Main.javapackage sample;import javafx.application.Application;import javafx.fxml.FXMLLoader;import javafx.scene.Parent;import javafx.scene.Scene;import javafx.stage.Stage;public class Main extends Application { @Override public void start(Stage primaryStage) throws Exception{ Parent root = FXMLLoader.load(getClass().getResource("sample.fxml")); primaryStage.setTitle("Hello World"); primaryStage.setScene(new Scene(root, 300, 275)); primaryStage.show(); } public static void main(String[] args) { launch(Main,args); }}Controller.javapackage sample;import javafx.collections.FXCollections;import javafx.fxml.Initializable;import javafx.scene.control.ListView;public class Controller implements Initializable { @Override public void initialize(URL url, ResourceBundle resourceBundle) { ListView<Integer> listView = new ListView<>(); listView.setItems(FXCollections.observableArrayList(1, 5, 8, 13)); Integer t = 5; listView.getSelectionModel().select(t); System.out.println(listView.getSelectionModel().getSelectedItems()); }}示例.fxml<?import javafx.geometry.Insets?><?import javafx.scene.layout.GridPane?><?import javafx.scene.control.Button?><?import javafx.scene.control.Label?><GridPane fx:controller="sample.Controller" xmlns:fx="http://javafx.com/fxml" alignment="center" hgap="10" vgap="10"></GridPane>您會注意到此代碼按預期工作,但我現在發現的是,因為我沒有使用 java 而是使用 groovy - 將文件結尾切換為 groovy 并使用 groovy 編譯器進行編譯使該程序具有我所描述的行為,即意味著問題與 groovy 相關,與 java 無關。
1 回答

Qyouu
TA貢獻1786條經驗 獲得超11個贊
您提出的問題有一個簡單的答案:
class Foo<T> {
void foo(int i) {
System.out.println("foo(int)");
}
void foo(T t) {
System.out.println("foo(T)");
}
}
private void test() {
Foo<Integer> foo = new Foo<>();
foo.foo(1);
foo.foo((Integer)1);
foo.foo(Integer.valueOf("1"));
}
印刷:
富(整數)
腳)
腳)
但是,我懷疑您已經嘗試過,所以請發布一些示例代碼。
如果您愿意,請在此處查看方法選擇規則: https ://docs.oracle.com/javase/specs/jls/se11/html/jls-5.html#jls-5.3 。
添加回答
舉報
0/150
提交
取消