Java.lang.Class.getDeclaredFields() 方法
描述
java.lang.Class.getDeclaredFields() 方法返回一个 Field 对象数组,包括公共、受保护、默认(包)访问和私有字段,但不包括继承的字段。 如果类或接口未声明任何字段,或者此 Class 对象表示原始类型、数组类或 void,则该方法返回长度为 0 的数组。
声明
以下是 java.lang.Class.getDeclaredFields() 方法的声明。
public Field[] getDeclaredFields() throws SecurityException
参数
NA
返回值
此方法返回表示该类的所有声明字段的 Field 对象数组。
异常
SecurityException − 如果存在安全管理员 s。
示例
下面的例子展示了 java.lang.Class.getDeclaredFields() 方法的使用。
package com.tutorialspoint;
import java.lang.reflect.*;
public class ClassDemo {
public static void main(String[] args) {
try {
ClassDemo c = new ClassDemo();
Class cls = c.getClass();
// returns the array of Field objects
Field[] fields = cls.getDeclaredFields();
for(int i = 0; i < fields.length; i++) {
System.out.println("Field = " + fields[i].toString());
}
} catch(Exception e) {
System.out.println(e.toString());
}
}
public ClassDemo() {
// no argument constructor
}
public ClassDemo(long l, int i) {
this.l = l;
this.i = i;
}
long l = 77688;
int i = 3;
}
让我们编译并运行上面的程序,这将产生下面的结果 −
Field = long com.tutorialspoint.ClassDemo.l Field = int com.tutorialspoint.ClassDemo.i

