如何获取泛型类型类的所有声明字段?

问题描述 投票:0回答:1

如何在 DatatableResult 这样的类中获取泛型类型 T 的所有声明字段,或者它可以是任何类,其中 T 可以是任何对象,并且我在编译时不知道 T 的类型?

例如请看下面的代码

import java.util.List;


public class DatatableResult<T> {

    private Integer totalRecords;

    private List<T> resultList;

    //setter & getter method
}
public class Employee {
    private String name;
    private String address;
    private String phone;
    private String email;

    // setter & getter method

}
java spring reflection
1个回答
0
投票
public static void main(String[] args) {
    // Create an instance of DatatableResult with a specific type
    DatatableResult<Employee> datatableResult = new DatatableResult<>();
    
    // Get the Class object of the type parameter T
    Class<Employee> clazz = Employee.class;
    
    // Get the fields of the Employee class
    List<String> fields = getDeclaredFields(clazz);
    
    System.out.println("Fields of Employee class:");
    for (String field : fields) {
        System.out.println(field);
    }

public static List<String> getDeclaredFields(Class<?> clazz) {
    List<String> fieldNames = new ArrayList<>();
    Field[] fields = clazz.getDeclaredFields();
    for (Field field : fields) {
        fieldNames.add(field.getName());
    }
    return fieldNames;
}
© www.soinside.com 2019 - 2024. All rights reserved.