5
import java.lang.reflect.Method;
import java.util.Arrays;

public class Test
{
     public static void main(String s[]) throws ClassNotFoundException
     {
        Class cls = Class.forName("Test");
        System.out.println("Class is "+cls);
        Method[] mtds = cls.getMethods();
        System.out.println("Methods are "+Arrays.deepToString(mtds));  // not having all methods
    }

    void reflectionTestMethod()
    {
        System.out.println("test");
    }
}

Output is

Class is class Test

Methods are [public static void Test.main(java.lang.String[]) throws java.lang.ClassNotFoundException, public final void java.lang.Object.wait() throws java.lang.InterruptedException, public final native void java.lang.Object.wait(long) throws java.lang.InterruptedException, public final void java.lang.Object.wait(long,int) throws java.lang.InterruptedException, public boolean java.lang.Object.equals(java.lang.Object), public java.lang.String java.lang.Object.toString(), public native int java.lang.Object.hashCode(), public final native java.lang.Class java.lang.Object.getClass(), public final native void java.lang.Object.notify(), public final native void java.lang.Object.notifyAll()]

Why is reflectionTestMethod() not available in the output ?

2 Answers 2

22

getMethods() returns public methods (as it states in its Javadoc)

Try getDeclaredMethods() instead or make the method public.

BTW, you can do:

Class cls = Test.class;
System.out.println("Class is " + cls);
for(Method method : cls.getDeclaredMethods())
    System.out.println(method);
Sign up to request clarification or add additional context in comments.

3 Comments

+1 for getDeclaredMethods. I'll try to give you your 100,000th point ;-)
@assylias I think you just did. ;) I try to give 500 point bounties to my questions, but even so...
Too late to take it back, I am still over. :D
4

Because that method is not public. The javadoc states (emphasis mine):

Returns an array containing Method objects reflecting all the public member methods of the class or interface represented by this Class object

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.