有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java获取类的方法

当使用反射获取某个具体类的方法时——即使我没有明确定义该类的任何方法——默认的超类(对象)方法(wait、equals、toString等)当其他只能通过反射(getSimpleName、isAnnotation、isSynthetic等)访问时返回不是

这是为什么

只有通过反射才能访问的方法是从输出中任意解析出来的,还是幕后发生了更有趣的事情

我如何将这一原则应用于我自己的具体类,以便getMethods()只返回我在类中显式定义的方法(或任意选择的方法,但这似乎非常高级),而不返回从类继承的默认方法


共 (1) 个答案

  1. # 1 楼答案

    否。所有引用类型的超类都是Object。这里定义了方法wait(..)equals(..)toString(),这些就是您得到的方法

    您列出的其他方法来自类Class,它是所有反射操作的入口点

    How can I apply this principle to my own concrete class so that getMethods() only returns the methods I explicitly define in my class (or arbitrarily choose, but that seems extremely advanced) and not the default methods which are inherited from Class?

    你不能用getMethods()。但是您可以使用^{}只获取在类中声明的那些方法,这些方法对应于调用它的Class对象

    Returns an array containing Method objects reflecting all the declared methods of the class or interface represented by this Class object, including public, protected, default (package) access, and private methods, but excluding inherited methods.