2016년 12월 2일 금요일

[Java Reflection REVIEW] 자바 리플렉션 사용기- 02




JAVA REFLECTION

What if You need to transfer Object to Map which means You are going to relocate your Object's private members to a Map. ALL. previously, We've seen how to do this. I would assume that you've already had my code in first '[Java Reflection REVIEW]자바리블렉션 사용기 -01'
Info info = new Info("name", "password", "alias", "address", "strength",
                     "etc1", "etc2");
ObjectToMap(map, Arrays.asList("name", "password", "alias",
 "address", "strength", "etc1", "etc2"), info);
But I want to code like this! Because always all of members in Info move into a Map.
ObjectToMap(map, info);
How is it possible. We'll use Reflection and collect perticular methods (which are getters) in invoke them. Firstly, make a method called "ObjectToMap"
private void ObjectToMap(Map map, Object sms) {
  List methods = getGetters(getMethods(sms), sms);
  for ( Method method : methods) {
    map.put(CamelToSnake(dropGet(method.getName())), invokeMethod(method,sms));
  }
}
You can see there is a for loop statement. We will get getMethods in Object via getGetters(); Second, create getGetters
private List getGetters(final Method[] methods, Object obj) {
  int len = methods.length;
  List res = new ArrayList();
 
  for(int i = 0; i < len ; i++) {
    if(methods[i] != null && methods[i].getName().startsWith("get") &&
            !methods[i].getName().endsWith("Class") ) {
      res.add(methods[i]);
    }
  }
  return res;
}

private Method[] getMethods(Object sms) {
  return sms.getClass().getMethods();
}
finally, INVOKE!!!!
private String invokeMethod( Method method, Object sms) {
  String res = null;
  try {
    res = String.class.cast(method.invoke(sms));
   
  } catch (Exception e) {
    e.printStackTrace();
  }
  return res;
}
You can test easily. I hope you enjoy my text. Your comments will help me blog. Thank you.

댓글 없음 :

댓글 쓰기