问题
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
回答1:
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]
.
回答2:
As it is int with flags you can compare them by bit operations.
int common = flags1 & flags2;
int only1 = flags1 ^ common;
int only2 = flags2 ^ common;
Then you can query only1
and only2
by Modifier
methods.
来源:https://stackoverflow.com/questions/17199409/comparing-modifiers-in-java