简体   繁体   中英

Varargs with different type in method overloading in Java

I have two function as follow:

public static Method findMethodBestMatch(String methodName, Class<?>... parameterTypes) {
}

public static Method findMethodBestMatch(String methodName, Object... args) {
}

Then when I call findMethodBestMatch("xx") , the compiler confused both function match. My question is how can I specify one method to call.

From what I know, if you have two methods that could be called but parameters of one are more specific than the other, then it runs the one more specific. In your example, Class is a subclass of Object and because of that it will always pick the first method.

However, if instead of Class... and Object... you would have Integer... and String... it won't compile. One of the two needs to extend the other one.

What it means that one method is more specific than other:

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 error. In cases such as an explicitly typed lambda expression argument (§15.27.1) or a variable arity invocation (§15.12.2.4), some flexibility is allowed to adapt one signature to the other.

You can read more in JLS

For your question on how to call a specific one: Object... is simply an array of Object . Because of that you could always just pass an empty array, like so:

findMethodBestMatch("xx", new Class<?>[0]); // calls the first implementation
findMethodBestMatch("xx", new Object[0]); // calls the second implementation

Since Class Class inherits from Class Object (as any class does) when you try to pass array of Class it could fit both methods. Leave just one method with Object... param and in the method differentiate between the different types.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM