Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java method overload choice [duplicate]

Tags:

java

I have two methods in a class...

public void method(String var1, String var2, Object var3) {
    //do stuff
}

public void method(String var1, String var2, Object[] var3) {
    //do stuff
}

When I make the following call... obj.method("string", "string", obj) the correct method is called, however, when I try to call obj.method("string", "string", obj[]) the first incarnation of that method is called.

Is there any annotation or "hint" I can give to make sure the method I anticipate being called will be called? I know an Object[] is anObject, but I would hope that at runtime the method with Object[] would be called before Object.

like image 291
El Guapo Avatar asked Oct 10 '13 13:10

El Guapo


1 Answers

Nope, for me this calls the second method as expected!

In the case where you want one to be called over the other, then the hint you'd give is usually a cast to the exact parameter type expected by the method (this cast will work even on null.) So using (Object)arr would force the first method to be called, but by default it will definitely call the second method (on all correct versions of the JVM anyway - contrary to popular belief, this scenario is covered explicitly in the JLS and thus is not ambiguous.)

like image 75
Michael Berry Avatar answered Oct 15 '22 01:10

Michael Berry