使用 Java 反射仅获取类的公共方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20366327/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get only public methods of a class using Java reflection
提问by Matter Cat
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
我正在尝试使用反射来获取在类中显式声明的所有公共方法(因此c.getMethods()
不会工作,因为它也获取超类方法)。我可以用
Method[] allMethods = c.getDeclaredMethods();
to grab methods from just that class, but I only want to use public ones.
从该类中获取方法,但我只想使用公共方法。
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!
在这一点上,我正在尝试获取修饰符并基于此执行某些操作,但由于某种原因,调试器中显示的修饰符值和修饰符值输出不同。例如,我有一个私有getNode
方法,当“修饰符”值出现2
在调试器中时,它输出为"1"
当我这样做时System.out.println(c.getModifiers())
。奇怪的。有没有另一种方法来获取公共方法,还是我错过了一些明显的东西?谢谢你的帮助!