Java 반사 메커니즘을 통해 객체 속성 값을 동적으로 설정하는 방법
/**
* MethodName: getReflection<br>
* Description: respXML
* User: liqijing
* Date:2015-7-19 12:42:55
* @param clzzName
* @param respXML
* @return
* @throws ClassNotFoundException
* @throws DocumentException
* @throws IllegalArgumentException
* @throws IllegalAccessException
* @throws InstantiationException
* @throws SecurityException
* @throws NoSuchFieldException
*/
public static <T> Object getReflection(String clzzName , String respXML) throws ClassNotFoundException, DocumentException, IllegalArgumentException, IllegalAccessException, InstantiationException, SecurityException, NoSuchFieldException{
Object o = Class.forName(clzzName).newInstance();
Class clz = Class.forName(clzzName).newInstance().getClass();
Document doc = null ;
doc = DocumentHelper.parseText(respXML);
Element el = doc.getRootElement();
for (Field f : clz.getDeclaredFields()){
Iterator it=el.elementIterator();
while(it.hasNext()){
Element elt = (Element) it.next();
if(f.getName().equals(elt.getName())){
f = clz.getDeclaredField(elt.getName());
f.setAccessible(true);
f.set(o, elt.getText());
}
}
}
return o;
}
Dear All:개발 과정에서 유사한 수요가 반사 동적 설정을 통해 속성 값을 설정하는 데 도움이 되기를 바랍니다.여러분과 함께 나누게 되어 기쁩니다. 감사합니다.
이상의 자바는 반사 메커니즘을 통해 대상의 속성 값을 동적으로 설정하는 방법은 바로 편집자가 여러분에게 공유한 모든 내용을 참고하고 저희를 많이 사랑해 주시기 바랍니다.
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
38. Java의 Leetcode 솔루션텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.