java.lang.Class.getDeclaredField()方法
java.lang.Class.getDeclaredField()方法用法实例教程 - 方法返回一个Field对象,它反映此Class对象所表示的类或接口的指定已声明字段。
描述
java.lang.Class.getDeclaredField()方法返回一个Field对象,它反映此Class对象所表示的类或接口的指定已声明字段。name参数是一个字符串,指定所需的字段的简单名称。
声明
以下是声明java.lang.Class.getDeclaredField()方法
publicField getDeclaredField(String name)throwsNoSuchFieldException,SecurityException
参数
· name -- This is the name of the field.
返回值
此方法返回这个类中的指定字段的Field对象。
异常
· NoSuchFieldException -- If a field withthe specified name is not found.
· NullPointerException -- 如果name 为 null.
· SecurityException -- If a security manager, s, ispresent.
实例
下面的例子说明了如何使用java.lang.Class.getDeclaredField()方法。
package com.yiibai;
import java.lang.reflect.*;
public class ClassDemo {
public static void main(String[] args) {
try {
ClassDemo c = new ClassDemo();
Class cls = c.getClass();
// field long l
Field lVal = cls.getDeclaredField("l");
System.out.println("Field = " + lVal.toString());
}
catch(Exception e) {
System.out.println(e.toString());
}
}
public ClassDemo() {
// no argument constructor
}
public ClassDemo(long l) {
this.l = l;
}
long l = 77688;
}
让我们来编译和运行上面的程序,这将产生以下结果:
Field=longClassDemo.l