Get only public methods of a class using Java reflection

与世无争的帅哥 提交于 2020-01-11 04:19:08

问题


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.

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!


回答1:


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
    }
}


来源:https://stackoverflow.com/questions/20366327/get-only-public-methods-of-a-class-using-java-reflection

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!