尽管我目前有一个用例,其中我有一个泛型类型,但我还没有找到它,它有一个 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
提交
取消