简体   繁体   中英

Method Overloading - Java

Actual Question: If it calls (1) then how can I make it so that it calls (2) ?

I have following methods signature

public void myMethod(String myStr, MyClass myClass) {...} // (1)

public void myMethod(Object... objects) {...} // (2)

Somewhere I make a call like

myMethod(new String("name"), new MyClass());

Which overloaded method will be called ? If it calls (1) then how can I make it so that it calls (2) ?

It will call (1) because the method resolution algorithm gives priority to methods that do not use varargs.

To force it to use (2) you can pass an array or cast the first parameter to Object :

myMethod(new Object[] { "name", new MyClass() });
//or
myMethod((Object) "name", new MyClass());

In Java, it takes the method which is most specific. This is according to Java JLS 15.12.2.5 .

This doc says:

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.

If you need to invoke the generic method instead, I think you need to cast each of the parameters to generic type Object as:

myMethod((Object) "hello", (Object) new MyClass());

Or, use as

myMethod(new Object[]{"name", new MyClass()});

I will put this simply. Given that you are calling the constructor and passing a String and a MyClass object, it will obviously call the overloaded method which takes two arguments which are a String as arg 1 and a MyClass object as arg 2.

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