繁体   English   中英

在使用反射检查类时,如何避免在Java中继承自Object类的方法?

[英]How to avoid methods inherited from Object class in Java when examining a class with reflection?

有没有办法避免从Object类继承的方法。 我有以下代码:

public void testGetMethods() {
    SomeClass sc = new SomeClass();
    Class c = sc.getClass();
    Method [] methods = c.getMethods();

    for (Method method : methods) {
        System.out.println(method.getName());
    }
}

一切都还可以,但它也返回Object类中的方法,如hashCode,getClass,notify,equals等。类SomeClass应该只有两个自己的方法,即m1和m2。

我只想打印这些方法(m1,m2)。 有什么办法可以实现吗?

使用Class类的getDeclaredMethods()方法

返回一个Method对象数组,这些对象反映由此Class对象表示的类或接口声明的所有方法。 这包括公共,受保护,默认(包)访问和私有方法,但不包括继承的方法。

Method[] declaredMethods = c.getDeclaredMethods();

您可以从Object(或其他类)中排除方法,如下所示:

Method[] methods2 = new Object().getClass().getMethods();
HashMap<Method, Boolean> hash = new HashMap<Method, Boolean>();

for (Method method : methods2) hash.add(method, false);

for (Method method : methods) {
    if (!hash.containsKey(method)) System.out.println(method.getName());
}

这将允许您使用继承的方法,这与@ rgettman的答案不同。 使用HashMap以便检查方法所在的类是在恒定时间内发生的,并且运行时是线性的。

暂无
暂无

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

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