簡體   English   中英

如何使用Reflection獲取類的某些字段

[英]How to get some fields of the class using 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;

因此,如果它是一個靜態變量,我可以檢查天氣是否靜態但是如何檢查天氣是否為參考場?

任何人都可以解決我的疑慮嗎? 我被困在這里。

您可以使用getType方法確定字段類型,然后僅使用必填字段。 對於此特定情況,您可以檢查歸檔是否類型為DateString


編輯:

使用注釋+反射

第1步:定義自定義注釋。 這里DesiredField是我們的自定義注釋

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

}   

第2步:使用DesiredField注釋適當的字段,你應該注釋dateOfBirthaadhaarNumber類的

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

看看Class.getDeclaredFields() 此方法僅為您提供在給定類中聲明的字段; 不返回繼承的字段。

此方法為您提供Field對象的數組。 使用Field.getModifiers()Modifier的實用程序方法(例如, Modifier.isStatic(...) ),您可以查找字段是私有,靜態,同步等。

您可以傳遞字段名稱以僅獲取該字段:

 Field f1 = BaseModel.class.getDeclaredField("dateOfBirth");
 Field f2 = BaseModel.class.getDeclaredField("aadhaarNumber");

檢索Modifier以進一步檢查:

 Modifier.isStatic(f1.getModifiers());
 Modifier.isPrivate(f1.getModifiers());

等等

獲取所選字段的反射

Field[] declaredFields = clas.getDeclaredFields();
    List requiredFileds =  Arrays.asList("dateOfBirth","aadhaarNumber");
    for(Field f:declaredFields) {
        if(requiredFileds.contains(f.getName())) {

        }
    }

檢查靜態字段

java.lang.reflect.Modifier.isStatic(field.getModifiers())

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM