Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Reflection: wait() method repeat thrice. Why?

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?

like image 534
Vishrant Avatar asked Dec 05 '22 23:12

Vishrant


2 Answers

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());
    }
}
like image 190
Ted Hopp Avatar answered Dec 31 '22 12:12

Ted Hopp


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)
like image 33
Jesper Avatar answered Dec 31 '22 10:12

Jesper