자바 - dto 또는 vo의 가변적(변수) 필드명으로 value 가져오기
IT&프로그래밍 2019. 9. 19. 16:32
프로그램 코딩 중 dto 또는 vo의 객체에 필드명을 던져서 값(value)을 가져오고 싶을때가 반드시 있을것이다.
예를 들어 testVo.getMemNo(); 이런식으로 memNo를 가져오고 싶은데 이는 고정적이다.
즉, getMemNo만 가져올수 있는것이다.
아래의 코드를 보면 'gubun'이라는 변수를 던져서 그에 해당하는 값을 가져올수 있다.
//gubun이라는 변수에 memNo와 같이 얻고싶은 필드명을 대입.
//arg는 Object로써 임의의 클래스를 받을 수 있다.
String resArgs = "";
Field field = ReflectionUtils.findField(arg.getClass(), gubun);
field.setAccessible(true);
resArgs = (String)ReflectionUtils.getField(field, arg);
예시 : 메소드구현부)
public static String getArgsFromParam(String gubun, Object... args) {
String resArgs = "";
try {
for (Object arg : args) {
if (arg != null) {
if (arg instanceof TestParam) {
Field field = ReflectionUtils.findField(arg.getClass(), gubun);
field.setAccessible(true);
resArgs = (String)ReflectionUtils.getField(field, arg);
...
}
...
}
...
}
...
}
return resArgs;
}
예시 : 호출부)
String memNo = this.getArgsFromParam("memNo", args);
ReflectionUtils를 이용 하면 된다.
'IT&프로그래밍' 카테고리의 다른 글
svn: error: The subversion command line tools are no longer provided by Xcode. 발생시 (0) | 2020.08.06 |
---|---|
자바 - 문자열의 원하는 byte만큼 자르기 (0) | 2019.09.19 |
xcrun: error: invalid active developer path (/Library/Developer/CommandLineTools) 발생 시 (0) | 2018.11.23 |
안드로이드 - android:scaleType (0) | 2018.11.07 |
그누보드5 자동방지(캡챠) 없애기 (0) | 2018.03.29 |