Java 反射如何知道同级字段值?

Java 反射如何知道同级字段值?,java,reflection,field,Java,Reflection,Field,我有以下课程: class CampaignBeanDto { Date startDate; @MyAnnotation Date endDate; } 我需要字段endDate 我应该知道对于相同的实例,哪个值有valuestartDate假设您在endDate上写了@MyAnnotation,我相信您想要的是检索一个带有注释的字段 您可以通过以下方式实现此目的: for(Field f : CampaignBeanDto.class.getFields())

我有以下课程:

class CampaignBeanDto {

    Date startDate;

    @MyAnnotation
    Date endDate;

}
我需要字段
endDate


我应该知道对于相同的实例,哪个值有value
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);

        }
}

我会避免依赖于字段的顺序(但我可能错了)。您不能扫描所有字段并找到一个具有正确注释的字段吗?如果我只有字段,如何获取对ActivityBeandTo实例的引用?您可以使用
ActivityBeandTo dto=new ActivityBeandTo()
创建一个字段,并使用
dto
作为引用(或使用现有字段)。“如果我只有字段,我如何才能获得对活动Bean和实例的引用?”你不能。
字段
未链接到实例。是的-数据库查询?我从你那部分获得它,所以我单击了你的答案有用..:)你可以编辑你知道吗