Get only public methods of a class using Java refl

2019-04-18 11: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条回答
老娘就宠你
2楼-- · 2019-04-18 11:34

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
    }
}
查看更多
登录 后发表回答