[英]Why come output as 9 when I call to display method using getModifiers() method in (Reflection of Java Methods)?
這是Dog
類,它包括display
和makesound
方法
class Dog {
// methods of the class
public static void display() {
System.out.println("I am a dog.");
}
private void makeSound() {
System.out.println("Bark Bark");
}
}
這是主課。
class Main {
public static void main(String[] args) {
// create an object of Dog
Dog d1 = new Dog();
// create an object of Class
// using getClass()
Class obj = d1.getClass();
// using object of Class to
// get all the declared methods of Dog
Method[] methods = obj.getDeclaredMethods();
// create an object of the Method class
for (Method m : methods) {
// get the access modifier of methods
int modifier = m.getModifiers();
System.out.println("Modifires " + modifier);
}
}
}
}
}
當我使用getModifiers
方法調用 make sound 方法時,輸出為 2,但 display 方法輸出為 9。這是為什么呢? 我認為顯示方法有 3 個訪問修改。 但是Modifier.toString(modifier)
將輸出顯示為公共和靜態的display
方法。
Method.getModifiers()
返回的int
值實際上是一個位域。 它允許通過執行按位或 ( |
) 操作將多個整數值(通常稱為標志)表示為單個整數。
各種修飾符的位標志值記錄在Modifier
類中。 這些是值:
修飾符 | 價值 |
---|---|
abstract |
1024 |
final |
16 |
interface |
512 |
native |
256 |
private |
2 |
protected |
4 |
public |
1 |
static |
8 |
strict |
2048 |
synchronized |
32 |
transient |
128 |
volatile |
64 |
(請注意,對於您的具體示例, public static
對應於1 | 8
,等於9
。)
您可以調用Modifier.toString()
來獲取文本表示,或使用其中一種實用程序方法來檢查是否存在某個修飾符。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.