本文介绍了方法重载和泛型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在选择哪种重载方法是正确的时,Java通常更喜欢普通方法,这可能会生成以下:

  public class GenericsTest {
public static void main(String [] args){
myMethod(Integer.class,10);
myMethod(String.class,overloaded method);
}

public static< T> void myMethod(Class< T> klass,T foo){
System.out.println(hello world);
}

public static< T> void myMethod(Class< T> klass,String bar){
System.out.println(bar);


$ / code $ / pre
$ b $输出:

  hello world 
重载方法



解决方案

不,不缺少更多具体过载。但是,如果他们的行为不同,他们应该有不同的名字。如果他们的行为一样,那么两者都无关紧要。


Java typically prefers normal methods to generic ones when choosing which overloaded method is correct, which could generate the following sscce:

public class GenericsTest {
    public static void main(String[] args) {
        myMethod(Integer.class, 10);
        myMethod(String.class, "overloaded method");
    }

    public static <T> void myMethod(Class<T> klass, T foo) {
        System.out.println("hello world");
    }

    public static <T> void myMethod(Class<T> klass, String bar) {
        System.out.println(bar);
    }
}

Output:

hello world
overloaded method

Is there any way to force Java to use the Generic version?

解决方案

No, not short of deleting or hiding the more specific overload. Yet, if they behave differently, they should simply have different names. And if they behave the same, it should not matter either way.

这篇关于方法重载和泛型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-16 08:23