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

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

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

Java.lang.Class 类getFields()方法用于获取该类的字段,即公共字段及其成员。该方法以 Field 对象数组的形式返回该类的字段。
句法:

public Field[] getFields()

参数:此方法不接受任何参数。
返回值:该方法以Field对象数组的形式返回该类的字段
异常如果存在安全管理器并且不满足安全条件,则此方法将引发SecurityException
下面的程序演示了 getFields() 方法。
示例 1:

Java
// Java program to demonstrate getFields() method
 
import java.util.*;
 
public class Test {
 
    public Object obj;
 
    public static void main(String[] args)
        throws ClassNotFoundException
    {
 
        // returns the Class object for this class
        Class myClass = Class.forName("Test");
 
        System.out.println("Class represented by myClass: "
                           + myClass.toString());
 
        // Get the fields of myClass
        // using getFields() method
        System.out.println("Fields of myClass: "
                           + Arrays.toString(
                                 myClass.getFields()));
    }
}


Java
// Java program to demonstrate getFields() method
 
import java.util.*;
 
class Main {
 
    private Object obj;
 
    Main()
    {
 
        class Arr {
        };
 
        obj = new Arr();
    }
 
    public static void main(String[] args)
        throws ClassNotFoundException
    {
        Main t = new Main();
 
        // returns the Class object
        Class myClass = t.obj.getClass();
 
        // Get the fields of myClass
        // using getFields() method
        System.out.println("Fields of myClass: "
                           + Arrays.toString(
                                 myClass.getFields()));
    }
}


输出:
Class represented by myClass: class Test
Fields of myClass: [public java.lang.Object Test.obj]

示例 2:

Java

// Java program to demonstrate getFields() method
 
import java.util.*;
 
class Main {
 
    private Object obj;
 
    Main()
    {
 
        class Arr {
        };
 
        obj = new Arr();
    }
 
    public static void main(String[] args)
        throws ClassNotFoundException
    {
        Main t = new Main();
 
        // returns the Class object
        Class myClass = t.obj.getClass();
 
        // Get the fields of myClass
        // using getFields() method
        System.out.println("Fields of myClass: "
                           + Arrays.toString(
                                 myClass.getFields()));
    }
}
输出:
Fields of myClass: []

参考: https://docs.oracle.com/javase/9/docs/api/ Java/lang/Class.html#getFields–