反射。如何知道兄弟场价值?

时间:2015-04-17 12:30:33

标签: java reflection field

我有以下课程:

class CampaignBeanDto {

    Date startDate;

    @MyAnnotation
    Date endDate;

}

我需要对字段endDate

的引用

我应该知道哪个值对于同一个实例

具有值startDate

2 个答案:

答案 0 :(得分:1)

假设你在@MyAnnotation之上写了endDate我相信你想要的是检索一个用注释注释的字段。

你可以这样做:

for(Field f : CampaignBeanDto.class.getFields())
{
    if(f.getAnnotation(MyAnnotation.class) != null)
    {
         //this is the field you are searching
    }
}

如果该字段始终命名为endDate,那么您只需执行以下操作:

for(Field f : CampaignBeanDto.class.getFields())
{
    if(f.getName().equals("endDate"))
    {
         //this is the field you are searching
    }
}

答案 1 :(得分:0)

以下代码将获取所提供实例的所有字段。它将扫描注释。将获得具有自定义注释的字段的所有值

Field[] fields = instance.getClass().getDeclaredFields();
if(instance.getAnnotation(MyAnnotation.class) != null){
        for (Field field : fields) {
            boolean access = field.isAccessible();
            field.setAccessible(true);

            //getting value
            System.out.println(field.get(instance));

            field.setAccessible(access);

        }
}