使用Java反射仅获取类的公共方法 [英] Get only public methods of a class using Java reflection

查看:160
本文介绍了使用Java反射仅获取类的公共方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用反射来获取在类中显式声明的所有公共方法(因此 c.getMethods()将无效,因为它会抓取超类方法也)。我可以使用

I'm trying to use reflection to grab all public methods that are declared explicitly in the class (so c.getMethods() won't work since it grabs superclass methods too). I can use

Method[] allMethods = c.getDeclaredMethods();

从该类中获取方法,但我只想使用公共方法。

to grab methods from just that class, but I only want to use public ones.

此时,我正在尝试抓取修改器并基于此执行某些操作,但由于某种原因,调试器中显示的修饰符值和修饰符值输出不是相同。例如,我有一个私有的 getNode 方法,而modifiers值在调试器中显示为 2 ,当我执行 System.out.println(c.getModifiers())时,它输出为1。奇怪的。有另一种方法可以获得公共方法,还是我错过了一些明显的东西?感谢您的帮助!

At this point, I'm trying to grab modifiers and do certain actions based on this, but for some reason the modifier value shown in the debugger and the modifier value output isn't the same. For example, I have a private getNode method that, while the "modifiers" value appears as 2 in the debugger, it outputs as "1" when I do System.out.println(c.getModifiers()). Weird. Is there another way to get just public methods, or am I missing something obvious? Thanks for any help!

推荐答案

我不知道您是如何使用 修饰符 ,但这里是如何使用的

I don't know how you are using Modifier, but here's how it's meant to be used

Method[] allMethods = Test.class.getDeclaredMethods();
for (Method method : allMethods) {
    if (Modifier.isPublic(method.getModifiers())) {
        System.out.println(method);
        // use the method
    }
}

这篇关于使用Java反射仅获取类的公共方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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