Method overloading and generics

爱⌒轻易说出口 提交于 2019-12-05 02:24:41

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.

One approach I've seen is to add a dummy parameter to the less frequently used method:

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

calling it like

myMethod(String.class, "overloaded method", null);

but otherwise

myMethod(String.class, "overloaded method");

calls the generic method.

Generic methods allow type parameters to be used to express dependencies among the types of one or more arguments to a method and/or its return type. If there isn't such a dependency, a generic method should not be used.

(from here)

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

Not without removing, renaming, or other wise changing the signature of the second method. (If you want to get really hacky – don't do this – use reflection to invoke the method.) That's because Java's overload resolution procedure will try to pick the most-specific method it can.

15.12.2.5. Choosing the Most Specific Method

If more than one member method is both accessible and applicable to a method invocation, it is necessary to choose one to provide the descriptor for the run-time method dispatch. The Java programming language uses the rule that the most specific method is chosen.

The informal intuition is that one method is more specific than another if any invocation handled by the first method could be passed on to the other one without a compile-time type error.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!