理解关于java反射中类的域及修饰符
Class类中的Filed[] getFields()方法返回的是类提供的public 域(Filed数组),getDeclaredFileds()返回的是类的全部域(Field数组)
域改如何理解?
(1)非静态域也称作实例变量(公有,私有属性);(2)静态域(静态变量,属于类)
一个实例:
class MyDemo { private int id; public String name; public static String city = "hangzhou"; }
class Demo5 extends MyDemo { private int newId; public String newName; }
public class Demo3 { public static void main(String[] args) { Demo5 demo = new Demo5(); Class cl = demo.getClass(); Field[] f1 = cl.getFields(); Field[] f2 = cl.getDeclaredFields(); System.out.println("显示当前类及超类的公有域:"); for (Field f : f1) { Class type = f.getType(); String name = f.getName(); String modifiers = Modifier.toString(f.getModifiers()); if (modifiers.length() > 0) System.out.print(modifiers+" "); System.out.println(type.getName()+" "+ name + ";"); }
System.out.println("只显示当前类的全部域:"); for (Field f : f2) { Class type = f.getType(); String name = f.getName(); String modifiers = Modifier.toString(f.getModifiers()); if (modifiers.length() > 0) System.out.print(modifiers + " " ); System.out.println(type.getName()+" "+ name + ";"); } } }
结果:
参考资料:类中定义的域http://book.2cto.com/201208/2874.html