📜  Java中的类 getDeclaredField() 方法和示例

📅  最后修改于: 2022-05-13 01:55:30.811000             🧑  作者: Mango

Java中的类 getDeclaredField() 方法和示例

Java.lang.Class 类getDeclaredField()方法用于获取该类的指定字段。该方法以Field对象的形式返回该类的指定字段。

句法:

public Field getDeclaredField(String fieldName)
       throws NoSuchMethodException,
              SecurityException

参数:此方法接受一个参数fieldName ,即要获取的字段。

返回值:该方法以Field对象的形式返回该类的指定字段

异常此方法抛出:

  • 如果未找到具有指定名称的字段,则NoSuchFieldException
  • 如果名称为空,则出现NullPointerException
  • 如果存在安全管理器并且不满足安全条件,则出现 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-