📅  最后修改于: 2023-12-03 15:02:00.463000             🧑  作者: Mango
在Java中,修饰符提供了控制类、方法、变量访问权限、继承性等的方式。Java的修饰符包括public、private、protected、default、static、final、abstract、native、synchronized、transient和volatile。同时,Java也提供了获取字段修饰符的方法fieldModifiers()。
Java中的fieldModifiers()
是Class类中的一个方法。它可以获取指定字段的访问修饰符。
方法声明如下:
public int fieldModifiers()
返回值是一个表示字段修饰符的整型值,其中各个修饰符的值如下:
| 修饰符 | 整型值 | |----------|--------| | public | 1 | | private | 2 | | protected| 4 | | static | 8 | | final | 16 | | volatile | 64 | | transient| 128 |
以下示例演示了如何使用fieldModifiers()
方法获取字段的修饰符。
import java.lang.reflect.Field;
public class FieldModifiersExample {
private static final int PUBLIC = 1;
private static final int PRIVATE = 2;
private static final int PROTECTED = 4;
private static final int STATIC = 8;
private static final int FINAL = 16;
private static final int VOLATILE = 64;
private static final int TRANSIENT = 128;
static int publicField;
private static int privateField;
protected static int protectedField;
static final int staticFinalField = 100;
volatile int volatileField;
transient int transientField;
public static void main(String[] args) throws Exception {
Class<?> clazz = FieldModifiersExample.class;
Field[] fields = clazz.getDeclaredFields();
for (Field field : fields) {
System.out.println("Field name: " + field.getName());
System.out.println("Field modifiers: " + fieldModifiers(field));
System.out.println("----------------------------------------");
}
}
private static String fieldModifiers(Field field) {
int modifiers = field.getModifiers();
StringBuilder sb = new StringBuilder();
if ((modifiers & PUBLIC) != 0) {
sb.append("public ");
} else if ((modifiers & PRIVATE) != 0) {
sb.append("private ");
} else if ((modifiers & PROTECTED) != 0) {
sb.append("protected ");
}
if ((modifiers & STATIC) != 0) {
sb.append("static ");
}
if ((modifiers & FINAL) != 0) {
sb.append("final ");
}
if ((modifiers & VOLATILE) != 0) {
sb.append("volatile ");
}
if ((modifiers & TRANSIENT) != 0) {
sb.append("transient ");
}
return sb.toString();
}
}
输出结果如下:
Field name: publicField
Field modifiers: static public
----------------------------------------
Field name: privateField
Field modifiers: static private
----------------------------------------
Field name: protectedField
Field modifiers: static protected
----------------------------------------
Field name: staticFinalField
Field modifiers: static final
----------------------------------------
Field name: volatileField
Field modifiers: volatile
----------------------------------------
Field name: transientField
Field modifiers: transient
----------------------------------------
可以看到,通过fieldModifiers()
方法,我们可以获取到各个字段的修饰符,从而更好地了解和掌握Java中修饰符的使用。