Search code examples
javareflectionmodifiers

Comparing modifiers in Java


In java you can use reflection to get an integer representing all the modifiers on a class. For example:

public final class Foo{}
Foo.getClass().getModifiers();//returns 17 because public=1 and final=16

My question is, what is the best way to compare the modifiers of two classes? Lets say we have another class:

private class Bar{}
Bar.getClass().getModifiers();//returns 2 because private=2

Now the simple way would be to have a ton of ifs saying modifier.isAbstract, modifier.isPublic, etc. But is there a cleaner way to do this?

Edit: In the end I want two lists. One says what Foo has that Bar doesn't, and the other one says what Bar has that Foo doesn't. So in this particular case I want:

FooHasBarDoesnt: public, final
BarHasFooDoesnt: private

Solution

  • What about the Modifier.toString() method?

    Return a string describing the access modifier flags in the specified modifier.

    e.g.

    List<String> modNames = Arrays.asList(Modifier.toString(mods).split("\\s"));
    

    This list looks like - [public, final].