比较Java中的修饰符 [英] Comparing modifiers in Java

查看:128
本文介绍了比较Java中的修饰符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在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

现在,最简单的方法是让大量的ifs声明modifier.isAbstract,modifier.isPublic等.但是有没有更清洁的方法呢?

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?

最后,我需要两个列表.一个说巴没有Foo,而另一个说巴没有Foo.因此,在这种情况下,我想要:

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

推荐答案

返回一个字符串,该字符串描述指定修饰符中的访问修饰符标志.

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

例如

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

此列表类似于-[public, final].

这篇关于比较Java中的修饰符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆