java - 如何使用反射获取类的某些字段

标签 java reflection

我有一个名为 Person.java 的类,它有自己的变量,还指向一些引用的类。看看下面的变量

public class Person extends BaseModel {
private static final long serialVersionUID = 1L;

private Date dateOfBirth;
private String aadhaarNumber;

private Set<EducationQualification> educationQualifications;
private Set<EmploymentExperience> employmentExperiences;
private ContactInformation contactInformation;
private DriversLicense driversLicense;
private PersonName personName;
private Candidate candidate;
private Passport passport;
private Set<Award> awards;
}

我在这里使用 Java 反射获取字段名称。当我使用 Class.getDeclaredField() 时,它会提供所有字段(指定变量上方)。但我只想要这两个领域

private Date dateOfBirth;
private String aadhaarNumber;

因此,如果它是一个静态变量,我可以检查 weather 是否为静态变量,但我如何检查 weather 是否为引用字段?

谁能解决我的疑惑?请我留在这儿。

最佳答案

您可以使用 getType方法来确定字段的类型,然后仅使用必填字段。对于这种特殊情况,您可以检查提交的类型是 Date 还是 String


编辑:

使用注解+反射

第 1 步:定义您的自定义注释。这里的DesiredField是我们自定义的注解

@Target(value = ElementType.FIELD)
@Retention(value = RetentionPolicy.RUNTIME)
public @interface DesiredField {

}   

第 2 步:DesiredField 注释适当的字段,您应该像

public class Person extends BaseModel {

    @DesiredField
    private Date dateOfBirth;
    @DesiredField
    private String aadhaarNumber;

    private Set<EducationQualification> educationQualifications;

    // Rest of the fields and methods

}

第 3 步:使用反射查找带注释的字段

  Person person = new Person();
  Field[] fields = person.getClass().getFields();

  for(Field field : fields){
      DesiredField annotation = field.getAnnotation(DesiredField.class);
      if( annotation != null ){
          // This is desired field now do what you want
      }
  } 

这可能有帮助:http://www.vogella.com/articles/JavaAnnotations/article.html

关于java - 如何使用反射获取类的某些字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17692429/

相关文章:

c# - 如何创建动态类型 List<T>

java - 获取所有字符串字段的值

javascript - 为 window.location 附加更改通知程序

java - 问题 : Java-Read socket (Bluetooth) input stream until a string (&lt;! MSG>) 被读取

java - 为什么我收到 NumberFormatException

Java lambda 参数类型未正确推断

java - android发布错误避免 fragment 中的non_default构造函数

java - 我需要几乎以这种方式设置JButton颜色,Help :

c# - 在 C#/.NET 中记录对文件的方法调用的最佳方式?

c# - 一种在开放委托(delegate)和封闭委托(delegate)之间执行转换的方法