我有以下课程:
class CampaignBeanDto {
Date startDate;
@MyAnnotation
Date endDate;
}
我需要对字段endDate
我应该知道哪个值对于同一个实例
具有值startDate
答案 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);
}
}