Comparing modifiers in Java

喜你入骨 提交于 2019-12-11 19:20:51

问题


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

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