java中foo(int)和foo(Integer)的区别

尽管我目前有一个用例,其中我有一个泛型类型,但我还没有找到它,它有一个 methodfoo(int)和一个 method 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());

    }

}

示例.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 无关。


陪伴而非守候
浏览 181回答 1
1回答

Qyouu

您提出的问题有一个简单的答案:class Foo<T> {&nbsp; &nbsp; void foo(int i) {&nbsp; &nbsp; &nbsp; &nbsp; System.out.println("foo(int)");&nbsp; &nbsp; }&nbsp; &nbsp; void foo(T t) {&nbsp; &nbsp; &nbsp; &nbsp; System.out.println("foo(T)");&nbsp; &nbsp; }}private void test() {&nbsp; &nbsp; Foo<Integer> foo = new Foo<>();&nbsp; &nbsp; foo.foo(1);&nbsp; &nbsp; foo.foo((Integer)1);&nbsp; &nbsp; foo.foo(Integer.valueOf("1"));}印刷:富(整数)脚)脚)但是,我怀疑您已经尝试过,所以请发布一些示例代码。如果您愿意,请在此处查看方法选择规则: https ://docs.oracle.com/javase/specs/jls/se11/html/jls-5.html#jls-5.3 。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java