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是Class Test
方法是[public static void Test.main(java.lang.String [])抛出java.lang.ClassNotFoundException, public final void java.lang.Object.wait()throws java.lang.InterruptedException,public final native void java.lang.Object.wait(long)抛出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()在输出中不可用?
答案 0 :(得分:17)
getMethods()
返回公共方法(正如它在Javadoc中所述)
请尝试使用getDeclaredMethods()
或将该方法设为公开。
Class cls = Test.class;
System.out.println("Class is " + cls);
for(Method method : cls.getDeclaredMethods())
System.out.println(method);
答案 1 :(得分:4)
因为该方法不公开。 javadoc states(强调我的):
返回一个数组,其中包含反映此Class对象所代表的类或接口的所有公共成员方法的Method对象