我有一个名为 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/