I was trying to get method names using Reflection, I have written below two classes:
package com.test;
public class Test {
private void method1() {
}
}
.
package com.test;
import java.lang.reflect.Method;
public class Test2 {
public static void main(String[] args) throws SecurityException, ClassNotFoundException {
Method[] m = Class.forName("com.test.Test").getMethods();
for (Method method : m) {
System.out.println(method.getName());
}
}
}
Instead of getDeclaredMethods()
I have used getMethods()
I got following output:
equals
hashCode
toString
getClass
notify
notifyAll
wait
wait
wait
My question is: why is the wait
method repeated thrice?
There are three methods named wait
defined in class Object
:
void wait()
void wait(long timeout)
void wait(long timeout, int nanos)
Your code is printing each method name, but not the argument type list, so they all look alike in the output. To see the parameter types, you could use something like this (which could be improved to provide better formatting:
for (Method method : m) {
System.out.println(method.getName());
for (Class<?> argClass : m.getParameterTypes()) {
System.out.println(" " + argClass.getName());
}
}
Because there are three overloaded versions of the wait
method, see the API documentation of class java.lang.Object
:
wait()
wait(long timeout)
wait(long timeout, int nanos)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With