简体   繁体   English

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

[英]java reflection: getMethods function not showing a method

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 类是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()] 方法是[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)抛出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 ? 为什么reflectionTestMethod()在输出中不可用?

getMethods() returns public methods (as it states in its Javadoc) getMethods()返回公共方法(因为它在Javadoc中声明)

Try getDeclaredMethods() instead or make the method public. 请尝试使用getDeclaredMethods()或将该方法getDeclaredMethods()公共。

BTW, you can do: 顺便说一下,你可以这样做:

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

Because that method is not public. 因为那种方法不公开。 The javadoc states (emphasis mine): javadoc陈述 (强调我的):

Returns an array containing Method objects reflecting all the public member methods of the class or interface represented by this Class object 返回一个包含Method对象的数组,这些对象反映此Class对象所表示的类或接口的所有公共成员方法

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM