MCPcopy Create free account
hub / github.com/castello/spring_basic / SetterCall

Class SetterCall

ch2/SetterCall.java:11–76  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

9import org.springframework.util.StringUtils;
10
11public class SetterCall {
12 public static void main(String[] args) throws Exception{
13 Map<String, String> map = new HashMap<>();
14 map.put("year", "2021");
15 map.put("month", "10");
16 map.put("day", "1");
17
18 Class<?> type = Class.forName("com.fastcampus.ch2.MyDate");
19
20 // MyDate인스턴스를 생성하고, map의 값으로 초기화한다.
21 Object obj = dataBind(map, type);
22 System.out.println("obj="+obj); // obj=[year=2021, month=10, day=1]
23 } // main
24
25 private static Object dataBind(Map<String, String> map, Class<?> clazz) throws Exception {
26 // 1. MyDate인스턴스 생성
27// Object obj = clazz.newInstance(); // deprecated method
28 Object obj = clazz.getDeclaredConstructor().newInstance(new Object[0]);
29
30 // 2. MyDate인스턴스의 setter를 호출해서, map의 값으로 MyDate를 초기화
31 // 2-1. MyDate의 모든 iv를 돌면서 map에 있는지 찾는다.
32 // 2-2. 찾으면, 찾은 값을 setter로 객체에 저장한다.
33 Field[] ivArr = clazz.getDeclaredFields();
34
35 for(int i=0;i<ivArr.length;i++) {
36 String name = ivArr[i].getName();
37 Class<?> type = ivArr[i].getType();
38
39 // map에 같은 이름의 key가 있으면 가져와서 setter호출
40 Object value = map.get(name); // 못찾으면 value의 값은 null
41 Method method = null;
42
43 try { // map에 iv와 일치하는 키가 있을 때만, setter를 호출
44 if(value==null) continue;
45
46 method = clazz.getDeclaredMethod(getSetterName(name), type); // setter의 정보 얻기
47 System.out.println("method="+method);
48 method.invoke(obj, convertTo(value, type)); // obj의 setter를 호출
49 } catch(Exception e) {
50 e.printStackTrace();
51 }
52 }
53
54 System.out.println(Arrays.toString(ivArr));
55
56 return obj;
57 }
58
59 private static Object convertTo(Object value, Class<?> type) {
60 // value의 타입과 type의 타입이 같으면 그대로 반환
61 if(value==null || type==null || type.isInstance(value))
62 return value;
63
64 // value의 타입과 type이 다르면, 변환해서 반환
65 if(String.class.isInstance(value) && type==int.class) // String -> int
66 return Integer.valueOf(""+value);
67
68 return value;

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected