[英]reflection. How to know sibling field value?
我有以下課程:
class CampaignBeanDto {
Date startDate;
@MyAnnotation
Date endDate;
}
我需要對字段endDate
的引用
我應該知道哪個值具有相同實例的值startDate
假設您在endDate
上寫了@MyAnnotation
,我相信您想要的是檢索一個使用某些注釋進行注釋的字段。
您可以這樣實現:
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
}
}
以下代碼將從提供的實例中獲取所有字段。 它將掃描注釋。 將獲得具有您的自定義注釋的字段的所有值
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);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.