【发布时间】:2019-02-25 15:48:51
【问题描述】:
虽然我目前有一个用例,其中我有一个泛型类型,它有一个方法foo(int) 和一个方法foo(T),但我一直没能找到它。
对于我的用例,类型是用 T = Integer 实例化的,这意味着我有方法 foo(int) 和 foo(Integer)。
每当我尝试调用foo(Integer) 时,它都会调用foo(int),无论是否指定了类型,无论我是否强制转换。解决它的唯一方法是使用 Long 代替,我不想这样做。
有什么办法可以强制java使用foo(Integer)方法?
编辑:
有一次,为了回答评论,我认为代码与此处无关,因为我所描述的内容足以理解我的意思。
其次,错误是在我的最后,我道歉。我没有预期的行为,并认为这是因为这方面的问题,特别是因为我的 IDE 显示了 foo(int) 方法的用法。我现在要关闭它
一个 MVCE:
Main.java
package 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.java
package 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());
}
}
sample.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 无关。
【问题讨论】:
-
请出示相关代码
-
这个简单的代码正好相反:
public class Foo<T> { void foo (int a){ } void foo (T a){ } public static void main(String[] args) { Foo<Integer> foo = new Foo<>(); foo.foo(Integer.valueOf(5)); // invoke the method with object parameter foo.foo(5); // invoke the method with int parameter } } -
@davidxxx 我认为您应该等待 OP 提供minimal reproducible example。当然,我们可以构建“相反”的例子;但是 OP 可能正在做一些不同的事情,并且没有充分解释这个问题,任何人都无法解释这个问题。
-
@Andy Turner 同意。没有理由着急。
-
@Folling 始终提供minimal reproducible example。代码说 1000 个单词,没有自然语言描述的细微差别:对提问者来说清楚的散文不一定对读者来说清楚;代码具有易于理解的语义。
标签: java generics methods parameters