获取声明的方法 - Java [英] Getting Declared Methods - Java

查看:118
本文介绍了获取声明的方法 - Java的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有以下三个类别

A.java

public class A {
    public static void main (String[] args) {
        new C();
    }
}

B.java / p>

B.java

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

public class B {
    public B() {
        Method[] m = this.getClass().getDeclaredMethods();
        System.out.println(Arrays.toString(m));
    }

    public void hello() {

    }
}

C.java

public class C extends B{
    public C() {
        super();
    }
}

我在类A中运行main方法。 ,它应该实例化类C,它应该调用类B的构造函数,打印出声明的方法。输出为 [] 。这是一个惊喜,因为我期待的输出是(假设所有的类都在包中称为 test ):

and I run the main method in class A. Well, it should instantiate class C, which in turn should call class B's constructor, to print out the declared methods. The output is []. This is a surprise to me, as I was expecting the output to be (assuming all classes are in package called test):

[public void test.B.hello()]

那么,怎么了?

推荐答案

getClass 返回实例的类。在这种情况下,这是 C 。类 C 中没有声明的方法。您也可以使用返回的 Class 对象的'getSuperClass'方法来解决您的问题:

getClass returns the class of the instance. In this case, this is C. There is no declared method in class C. You can solve your problem by also using the 'getSuperClass' method of the returned Class object:

Class c = this.getClass();
while (c != null) {
  System.out.println(Arrays.toString(c.getDeclaredMethods()));
  c = c.getSuperClass();
}

这篇关于获取声明的方法 - Java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆