getModifiers() 的 Java 文档如下:
int getModifiers()
Returns the Java language modifiers for the member or constructor represented by this Member, as an integer. The Modifier class should be used to decode the modifiers in the integer.
和 Java Docs 也提供了 list of different modifiers and their corresponding int values :
public static final int ABSTRACT 1024
public static final int FINAL 16
public static final int INTERFACE 512
public static final int NATIVE 256
public static final int PRIVATE 2
public static final int PROTECTED 4
public static final int PUBLIC 1
public static final int STATIC 8
public static final int STRICT 2048
public static final int SYNCHRONIZED 32
public static final int TRANSIENT 128
public static final int VOLATILE 64
对于单个修饰符,getModifiers() 非常简单。它只是返回与修饰符对应的常量值(例如,当我将一个类声明为 public final 并调用 getModifiers() 它返回 17)。
System.out.println("modifierValue:" + MyClass.class.getModifiers());
输出是:
17
但是,我不太明白它如何适用于多个修饰符。谁能赐教一下?
最佳答案
TL;DR: 它将它们加在一起形成一个 bit field .
要理解这一点,您需要了解二进制的工作原理,这类似于十进制 - 让我们从这里开始:
1 - public
10 - static
100 - final
那么,101
是什么意思?它必须是 public final
,因为除了单个 100
和单个 1< 之外,在十进制系统中没有其他方法可以生成“一百零一”/
.
现在将其扩展为二进制:
1 - public
2 - private
4 - protected
8 - static
9
是什么意思?好吧,与十进制系统一样,只有一种(正确的)方法可以将 9
转换为二进制 - 一个 8
和一个 1
。
现在我们使用所谓的位域,二进制的9
是:
1001
要验证,写一些代码!
public static void main(String[] args) throws Exception {
int i = 9;
System.out.println(Integer.toBinaryString(i));
}
现在,在十进制系统中,我们将重复除以 10
并检查最右边的数字(最低有效位)。对于二进制,这个过程是相同的,除了我们除以 2
- 这被称为位移。
public static void main(String[] args) throws Exception {
int i = 9;
System.out.println(Integer.toBinaryString(i));
i >>= 1;
System.out.println(Integer.toBinaryString(i));
i >>= 1;
System.out.println(Integer.toBinaryString(i));
i >>= 1;
System.out.println(Integer.toBinaryString(i));
}
输出:
1001
100
10
1
所以,如果我知道 private
是 21 值,并且我们知道我们有多少位,那么只需要移动正确的位数用 2
取模:
public static void main(String[] args) throws Exception {
int i = 9;
i >>= 2;
System.out.println(i%2);
}
输出:
0
所以我们基本上使用 1
和 0
值组成一个二进制数来存储 boolean 值。
所以把这个例子带入阅读世界:
public static void main(String[] args) throws Exception {
final Method method = App.class.getMethod("myMethod");
final int modifiers = method.getModifiers();
System.out.println(modifiers);
System.out.println(Integer.toBinaryString(modifiers));
}
public strictfp synchronized static final void myMethod() {
}
输出:
2105
100000111001
所以我们可以看到我们有:
20 = 1 - true
21 = 2 - 假
22 = 4 - 假
23 = 8 - 真
24 = 16 - true
25 = 32 - true
27 = 64 - 假
28 = 128 - 假
29 = 256 - 假
210 = 512 - 假
211 = 1024 - 假
212 = 2048 - true
关于java - getModifiers() 方法如何计算多个修饰符的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30666487/