Reputation: 21
I am using reflection APIs to do some queries on Java methods. Below is the code snippet to find out the return type of calling, say new java.lang.StringBuilder().append('a')
:
Class<?> c = Class.forName("java.lang.StringBuilder");
Method[] mList = c.getMethods();
for (int i = 0; i < mList.length; i++) {
if (mList[i].getName() == "append"
&& mList[i].getParameterTypes().length == 1
&& mList[i].getParameterTypes()[0].getCanonicalName() == "char") {
System.out.println(mList[i]);
}
}
Oddly, the output gives
public java.lang.AbstractStringBuilder java.lang.StringBuilder.append(char)
public java.lang.Appendable java.lang.StringBuilder.append(char) throws java.io.IOException
public java.lang.StringBuilder java.lang.StringBuilder.append(char)
while the Java API Specification only gives StringBuilder
as the return type. Does that mean the method append
actually overloads on return type?
Upvotes: 2
Views: 63
Reputation: 62864
When you invoke c.getMethods()
the resulting array will contain all the methods, that are defined in the StringBuilder
class and it superclass(es)/superinterface(s).
That's why you get three instead of one.
Does that mean the method
append
actually overloads on return type?
No. Overloading is a term that is strongly related to the method signature definition. The method signature includes:
Overloading specifies two or more methods with the name, but different method signature. The return-type is not part of the method signature.
In your example, the three method definitions are not overloaded, but overridden versions of one and the same method abstraction.
Upvotes: 1
Reputation: 36304
From javadocs we have :
Returns an array containing Method objects reflecting all the public member methods of the class or interface represented by this Class object, including those declared by the class or interface and those inherited from superclasses and superinterfaces. Array classes return all the (public) member methods inherited from the Object class. The elements in the array returned are not sorted and are not in any particular order. This method returns an array of length 0 if this Class object represents a class or interface that has no public member methods, or if this Class object represents a primitive type or void.
StringBuilder extends AbstractStringBuilder
AbstractStringBuilder implements Appendable
That's why you get 3 methods.
Upvotes: 1