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:
개발 과정에서 유사한 수요가 반사 동적 설정을 통해 속성 값을 설정하는 데 도움이 되기를 바랍니다.여러분과 함께 나누게 되어 기쁩니다. 감사합니다.
이상의 자바는 반사 메커니즘을 통해 대상의 속성 값을 동적으로 설정하는 방법은 바로 편집자가 여러분에게 공유한 모든 내용을 참고하고 저희를 많이 사랑해 주시기 바랍니다.

좋은 웹페이지 즐겨찾기