简体   繁体   English

我反射时如何知道最后一个物体?

[英]How can I know the last object when I reflect?

I have a DTO like this, 我有这样的DTO,

ADto{
  BDto bDto;
  Cto cDto;
}

BDto{
  String a1;
  String b1;
  int b1;
}

CDto{
  String a2;
  String b2;
  int b2;
}

When I use reflect,I want to get the BDto and CDto in ADto Object.Code like this: 当我使用反映,我想获得BDtoCDtoADto Object.Code这样的:

 for (Field field : aObj.getClass().getDeclaredFields()) {
            try {
                Object fieldValue = field.get(object);
 //todo  how to collect all String value  in `BDto` and `CDto` of aObj
                if (fieldValue instanceof String) {
                    shouldCheckFieldValues.add((String) fieldValue);
                }
            } catch (Exception e) {
                logger.error("some error has happened when fetch data in loop", e);
            }

        }
    }

I want to collect all String value in BDto and CDto of aObj?How can I achieve this? 我想收集BDtoCDto的所有String值?如何实现? Or how can I know the field which I have to recursive traversal with no hard code? 还是我怎么知道没有硬编码就必须递归遍历的字段?

You directly try to get the String attributes from ADto class, you can't. 您不能直接尝试从ADto类获取String属性。

First get the BDto attribute, then retreive Strings attributes. 首先获取BDto属性,然后获取字符串属性。 Do the same for CDto attribute 对CDto属性执行相同的操作

for (Field field : aObj.getClass().getDeclaredFields()) {
        try {
            Object fieldValue = field.get(object);
            //todo  how to collect all String value  in `BDto` and `CDto` of aObj
            if (fieldValue instanceof BDto) {
                for (Field field2 : fieldValue.getClass().getDeclaredFields()) 
                    if (field2 instanceof String) {
                        shouldCheckFieldValues.add((String) field2 );

Hope this helps 希望这可以帮助

static void exploreFields(Object aObj) {
    for (Field field : aObj.getClass().getDeclaredFields()) {

        try {
            Object instance_var = field.get(aObj);
            if (instance_var instanceof String) {
                System.out.println(instance_var);

            } else if(!(instance_var instanceof Number)) {
                exploreFields(instance_var);
            }
        } catch (Exception e) {
            logger.error("some error has happened when fetch data in loop", e);
        }
    }
}

Edited based on comment. 根据评论进行编辑。 Be aware your objects should not have circular dependencies. 请注意,您的对象不应具有循环依赖关系。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM