方法java.lang.Class.getDeclaredFields()返回一个字段对象数组。这些字段对象包括具有公共,私有,受保护和默认访问权限的对象,但不包括继承的字段。
另外,getDeclaredFields()如果类或接口没有声明的字段,或者在Class对象中表示原始类型,数组类或void ,则该方法返回零长度数组。
演示此的程序如下所示-
示例package Test;
import java.lang.reflect.*;
public class Demo {
int i;
char c;
public Demo(int i, char c) {
this.i = i;
this.c = c;
}
public static void main(String[] args) {
try {
Demo obj = new Demo(7, 'A');
Class c = obj.getClass();
Field[] fields = c.getDeclaredFields();
for(int i = 0; i
System.out.println("The field is: " + fields[i].toString());
}
} catch(Exception e) {
System.out.println(e.toString());
}
}
}
输出结果The field is: int Test.Demo.i
The field is: char Test.Demo.c
现在让我们了解上面的程序。
在该main()方法中创建了Demo类的对象。然后,数组fields []存储使用方法获得的字段对象getDeclaredFields()。然后使用for循环显示这些字段。演示这的代码片段如下-Demo obj = new Demo(7, 'A');
Class c = obj.getClass();
Field[] fields = c.getDeclaredFields();
for(int i = 0; i
System.out.println("The field is: " + fields[i].toString());
}