java.lang.Class类的getDeclaredField()方法用于获取此类的指定字段。该方法以Field对象的形式返回此类的指定字段。
用法:
public Field getDeclaredField(String fieldName) throws NoSuchMethodException, SecurityException
参数:此方法接受参数fieldName,这是要获取的Field。
返回值:此方法以Field对象的形式返回此类的指定字段。
异常该方法抛出:
- NoSuchFieldException如果找不到具有指定名称的字段。
- NullPointerException 如果名称为null
- SecurityException如果存在安全管理员并且不满足安全条件。
下面的程序演示了getDeclaredField()方法。
示例1:
// Java program to demonstrate // getDeclaredField() method import java.util.*; public class Test { public Object obj; public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException { // returns the Class object for this class Class myClass = Class.forName("Test"); System.out.println("Class represented by myClass: " + myClass.toString()); String fieldName = "obj"; // Get the field of myClass // using getDeclaredField() method System.out.println( fieldName + " Field of myClass: " + myClass.getDeclaredField(fieldName)); } }
输出:Class represented by myClass: class Test obj Field of myClass: public java.lang.Object Test.obj
示例2:
// Java program to demonstrate // getDeclaredField() method import java.util.*; class Main { private Object obj; public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException { // returns the Class object for this class Class myClass = Class.forName("Main"); System.out.println("Class represented by myClass: " + myClass.toString()); String fieldName = "obj"; try { // Get the field of myClass // using getDeclaredField() method System.out.println( fieldName + " Field of myClass: " + myClass.getDeclaredField(fieldName)); } catch (Exception e) { System.out.println(e); } } }
输出:Class represented by myClass: class Main obj Field of myClass: private java.lang.Object Main.obj
参考: https://docs.oracle.com/javase/9/docs/api/java/lang/Class.html#getDeclaredField-java.lang.String-
相关用法
- Java Class getEnclosingMethod()用法及代码示例
- Java Class getDeclaringClass()用法及代码示例
- Java Class getModifiers()用法及代码示例
- Java Class getEnclosingClass()用法及代码示例
- Java Class getComponentType()用法及代码示例
- Java Class isAnnotationPresent()用法及代码示例
- Java Class getAnnotation()用法及代码示例
- Java Class getEnclosingConstructor()用法及代码示例
- Java Class getMethod()用法及代码示例
- Java Class getGenericInterfaces()用法及代码示例
- Java Class getConstructor()用法及代码示例
- Java Class getDeclaredConstructor()用法及代码示例
- Java Class getDeclaredMethod()用法及代码示例
- Java Class getSuperclass()用法及代码示例
- Java Class getName()用法及代码示例
注:本文由纯净天空筛选整理自srinam大神的英文原创作品 Class getDeclaredField() method in Java with Examples。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。