2016-07-26 68 views
0

我有一个DTO这样,当我反思时,我如何知道最后一个对象?

ADto{ 
    BDto bDto; 
    Cto cDto; 
} 

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

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

当我使用反映,我想获得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); 
      } 

     } 
    } 

我想收集所有的字符串aObj的BDtoCDto的值如何实现?或者我怎么能知道我没有硬代码递归遍历的领域?

+0

您的标题与您的问题有任何关系吗? – EJP

回答

0

您直接尝试从ADto类获取字符串属性,则不能。

首先获取BDto属性,然后检索字符串属性。做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); 
+0

我想提取一个通用的reflectUtil,而不是像'BDto'这样的细节DTO硬代码。 –

0

希望这有助于

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); 
     } 
    } 
} 

编辑基于评论。注意你的对象不应该有循环依赖。

+0

不仅两个Dto,可能有BDD中的XDto。它是嵌套的。 –

相关问题