如何解决java中方法的泛型输入参数

时间:2018-05-14 15:36:31

标签: java generics

以下内容无法编译。 我该如何解决? 我想要一种方法或方法来接受泛型类型作为方法的输入,并将其委托给具体方法而不使用instanceof或反射。

public class MyCoolClass {

    void doSomthing(Double x) {}

    void doSomthing(Integer x) {}

    public <T extends Number> void setMe(T in) {

        doSomthing(in);

    }
}

3 个答案:

答案 0 :(得分:1)

  

我想要一种方法或方法来接受泛型类型作为方法的输入,并将其委托给具体方法而不使用instanceof或反射。

如果您控制泛型类型,则反转控件并将行为移动到泛型类型的界面中:

public interface MyInterface {
    void doSomething();
}

然后,您MyInterface的具体实施将知道该怎么做,从而避免instanceof和反思。

答案 1 :(得分:0)

What you are asking is not possible to do safely... you need the instance-of. ... however you need to ask whether your are doing the right thing here.

The only way to avoid the instance of is for the type to be known and compilation time and in that case the invoking code should be capable of calling the right concrete doSomething method.

Otherwise somewhere, either inside your class or the invoking code must do that annoying instance-of

Non-instance of alternatives would fall into using java reflection API which is far worse.

答案 2 :(得分:0)

你的问题的答案似乎是这样的: Java不是C ++。使用方法重载。

为您的示例类替换类似的内容:

public class MyActuallyFunctioningClass
{
    public Integer blam(final Integer paramName) {}
    public Double blam(final Double paramName) {}
}

使用Integer参数时,将调用Integer版本 当您使用Double参数时,将调用Double版本。