如何使用java反射查找成员的访问修饰符 [英] How to find the access modifier of a member using java reflection
问题描述
使用java反射查找成员的访问修饰符
Find the access modifier of a member using java reflection
private final static long serialId = 1L;
protected String title;
public String FirstName;
我需要知道哪个变量是私有的,受保护的还是公共的?
I need to know which variable is private, protected and public?
推荐答案
如果您有一个类(在 Vlucht 下面的代码中),那么您可以使用方法 getDeclaredFields() ...
然后每个字段实例都可以调用 getModifiers 方法,这些方法在下表中有说明。
If you have a class (in the code below Vlucht ) then you can use the method getDeclaredFields()... then every field instance can invoke the method getModifiers which are explainted in the table below..
反射自jdk1.5以来API一直是相同的,所以java8与反射无关,但更多的是使用流或类似的方式访问字段数组..
Reflection API has been the same since jdk1.5 so java8 is not relevant for reflection but more for accessing the array of fields using streams or similar..
如果你真的需要什么的话人类可读如:
if you really need something Human readable like :
private static final
private static final
protected or public
protected or public
然后使用 System.out.println(Modifier.toString(mod));
System.out.println(Modifier.toString(mod));
System.out.println(Modifier.toString(mod));
public class Vlucht {
private final static long serialId = 1L;
protected String title;
public String FirstName;
public static void main(String[] args) {
Field[] reflectedClass = Vlucht.class.getDeclaredFields();
for (Field field : reflectedClass) {
int mod = field.getModifiers();
System.out.println(mod);
}
}
}
这篇关于如何使用java反射查找成员的访问修饰符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!