普通はjava反射内省とBenUtilsツールバッグを使ってjavaBeanを操作します.
4434 ワード
/** * beanUtilsツールバッグを使う 第三者jarを導入する必要があります. * commons-beanutils-1.8.3.jar * commons-loging-11.jar */
package com.sg.reflex.test;
import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.PropertyUtils;
import com.sg.bean.TestBeanReflex;
public class TestNeiXing {
public static void main(String[] args)throws Exception {
TestBeanReflex br = new TestBeanReflex("2", "5");
String propertyName = "x";
String returnValue = getProperty(br, propertyName);
System.out.println(returnValue);
Object value = "3";
setProperty(br, propertyName, value);
System.out.println(br.getX());
/**
* BeanUtils bean bean
*/
System.out.println(BeanUtils.getProperty(br, propertyName));
System.out.println(BeanUtils.getProperty(br, propertyName).getClass().getName());//java.lang.String
/**
* BeanUtils bean
*/
BeanUtils.setProperty(br, propertyName, "5");
System.out.println(br.getX());
/**
* BeanUtils bean
*/
BeanUtils.setProperty(br, "brithDay.time", "111");
System.out.println(BeanUtils.getProperty(br,"brithDay.time"));// 111
/**
* beanUtils bean map
*/
Map map = BeanUtils.describe(br);
/*Iterator iterator = map.entrySet().iterator();
while(iterator.hasNext()){
String key = (String)iterator.next();
map.get(key);
}
Set set = map.keySet();
for(Object object : set){
System.out.println("key : "+object + "value : " + map.get(object));
}*/
/**
* PropertyUtils bean
*/
PropertyUtils.setProperty(br, "z", 9);
System.out.println(BeanUtils.getProperty(br, "z"));//
System.out.println(BeanUtils.getProperty(br, "z").getClass().getName());//
}
public static void setProperty(TestBeanReflex br, String propertyName,
Object value) throws IntrospectionException,
IllegalAccessException, InvocationTargetException {
PropertyDescriptor descriptor = new PropertyDescriptor(propertyName, br.getClass());
Method method = descriptor.getWriteMethod();
method.invoke(br, value);
}
public static String getProperty(TestBeanReflex br, String propertyName)
throws IntrospectionException, IllegalAccessException,
InvocationTargetException {
/*PropertyDescriptor descriptor = new PropertyDescriptor(propertyName, br.getClass());
Method method = descriptor.getReadMethod();
String returnValue = (String)method.invoke(br);
return returnValue;*/
//
// javaBean
BeanInfo beanInfo = Introspector.getBeanInfo(br.getClass());
// javaBean
PropertyDescriptor[] pds = beanInfo.getPropertyDescriptors();
String returnValue = null;
//
for(PropertyDescriptor pd : pds){
//
if (pd.getName().equals(propertyName)) {
// get
Method method = pd.getReadMethod();
returnValue = (String)method.invoke(br);
break;
}
}
return returnValue;
}
}