Reputation: 36984
I have following class:
class CampaignBeanDto {
Date startDate;
@MyAnnotation
Date endDate;
}
I need the reference to field endDate
I should know which value has value startDate
for same instance
Upvotes: 1
Views: 137
Reputation: 363
The following code will get all the fields from the instance provided. It will scan the annotations. will get all the value of the fields having your custom annotation
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);
}
}
Upvotes: 0
Reputation: 21004
Assuming you wrote @MyAnnotation
on top of endDate
I believe what you want is to retrieve a field which is annotated with some annotation.
You can achieve this that way :
for(Field f : CampaignBeanDto.class.getFields())
{
if(f.getAnnotation(MyAnnotation.class) != null)
{
//this is the field you are searching
}
}
If the field is always named endDate
then you can simply do :
for(Field f : CampaignBeanDto.class.getFields())
{
if(f.getName().equals("endDate"))
{
//this is the field you are searching
}
}
Upvotes: 1