java反射:getMethods函数没有显示方法

java reflection: getMethods function not showing a method

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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");
    }
}

输出是

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()]

为什么ReflectionTestMethod()在输出中不可用?


getMethods()返回公共方法(如其javadoc中所述)

改为尝试getDeclaredMethods()或将该方法公开。

顺便说一句,你可以:

1
2
3
4
Class cls = Test.class;
System.out.println("Class is" + cls);
for(Method method : cls.getDeclaredMethods())
    System.out.println(method);


因为该方法不是公共的。JavaDoc声明(Emphasis Mine):

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