The Java Reflection: wait () method is repeated three times. What for?

I tried to get method names using Reflection, I wrote 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 getDeclaredMethods()I used getMethods(), I got the following output:

equals
hashCode
toString
getClass
notify
notifyAll
wait
wait
wait

My question is: Why is the method waitrepeated three times?

+4
source share
3 answers

There are three named methods waitdefined in the class Object:

void wait()
void wait(long timeout)
void wait(long timeout, int nanos)

Your code prints the name of each method, but not a list of argument types, so they all look the same in output. To look at parameter types, you can use something like this (which can 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());
    }
}
+8

wait, . API java.lang.Object:

wait()
wait(long timeout)
wait(long timeout, int nanos)
+5

java.lang.Objectreally has three methods wait- one that takes no arguments, one of which takes long, and one that takes values longand int.

+1
source

All Articles