잡동사니를 모아두는 서랍장
Java Reflection 으로 인스턴스 생성하는 예시 본문
아래는 테스트 코드
package com.kakao.keyword;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
public class ReflectionTest<T> {
private Class<T> clazz;
@BeforeEach
public void init() {
clazz = (Class<T>) TestClass.class;
}
@Test
public void test() throws Exception {
T instance = clazz.getDeclaredConstructor().newInstance();
Field[] fields = clazz.getDeclaredFields();
for (int i = 0; i < fields.length; i++) {
System.out.println(fields[i].getName() + ", " + fields[i].getType());
injectValue(instance, fields[i]);
System.out.println(callGetter(instance, fields[i].getName()));
}
}
private void injectValue(Object obj, Field field) {
Class<?> typeClass = field.getType();
String fieldName = field.getName();
if (typeClass == Integer.class) {
callSetter(obj, fieldName, 10);
} else if (typeClass == Long.class) {
callSetter(obj, fieldName, 20L);
} else {
callSetter(obj, fieldName, "string");
}
}
private void callSetter(Object obj, String field, Object value) {
PropertyDescriptor pd;
try {
pd = new PropertyDescriptor(field, obj.getClass());
pd.getWriteMethod().invoke(obj, value);
} catch (Exception e) {
e.printStackTrace();
}
}
private Object callGetter(Object obj, String field) {
PropertyDescriptor pd;
try {
pd = new PropertyDescriptor(field, obj.getClass());
return pd.getReadMethod().invoke(obj);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
//getter, setter 는 lombok 으로 대체하는게 코드 수가 줄어 좋음.
static class TestClass {
private String memberString;
private Long memberLong;
private Integer memberInteger;
public String getMemberString() {
return this.memberString;
}
public void setMemberString(String memberString) {
this.memberString = memberString;
}
public Long getMemberLong() {
return this.memberLong;
}
public void setMemberLong(Long memberLong) {
this.memberLong = memberLong;
}
public Integer getMemberInteger() {
return this.memberInteger;
}
public void setMemberInteger(Integer memberInteger) {
this.memberInteger = memberInteger;
}
}
}
결과
memberString, class java.lang.String
string
memberLong, class java.lang.Long
20
memberInteger, class java.lang.Integer
10
'Java' 카테고리의 다른 글
jar 파일 실행 시 내부 리소스를 못읽는다면 확인해볼 사항 (0) | 2021.04.16 |
---|---|
객체지향 5원칙(SOLID) (0) | 2020.12.02 |
jar, war, ear 차이 (0) | 2020.02.01 |
Comments