/** * 改类掩饰了如何通过java.bean的类去获知bean中的属性并调用相应的set get方法 */ import java.beans.*; import java.lang.reflect.Method; public class JavaBeanInvoke { public static void main(String args[])throws Exception{ test1(); } public static void test1()throws Exception{ Person person = Person.class.newInstance(); BeanInfo beaninfo = Introspector.getBeanInfo(Person.class); PropertyDescriptor[] porpertydescriptors = beaninfo.getPropertyDescriptors(); for(PropertyDescriptor pd:porpertydescriptors){ System.out.println(pd.getName()); if(pd.getName().endsWith("name")){ Method setMethod=pd.getWriteMethod(); Method getMethod=pd.getReadMethod(); setMethod.invoke(person,"ShenZiping"); System.out.println(getMethod.invoke(person)); break; } } } public static void test2() throws Exception{ Person person = Person.class.newInstance(); PropertyDescriptor pd = new PropertyDescriptor("age",Person.class); Method setMethod = pd.getWriteMethod(); Method getMethod = pd.getReadMethod(); setMethod.invoke(person, 56); System.out.println(getMethod.invoke(person)); } }
/** * 代码举例了beanUtil包的普遍用法,需要apache的logging包和beanUtils包 */ import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashMap; import java.util.Map;
import org.apache.commons.beanutils.*; public class BeanUtilsInvoke { public static void main(String args[])throws Exception{ test1(); test2(); test3(); test4(); myConvertTest(); } public static void test1()throws Exception{ Person person = new Person(); BeanUtils.copyProperty(person, "name", "ShenZiping"); System.out.println("test1"+person.getName()); } public static void test2() throws Exception{ Person person = new Person(); Map<String, String> map = new HashMap<String, String>(); map.put("name", "ShenZiping"); map.put("age", "65"); BeanUtils.populate(person, map); System.out.println("test2"+person.getAge()); System.out.println("test2"+person.getName()); } public static void test3() throws Exception{ Person p1 = new Person(); Person p2 = new Person(); p1.setAge(98); p1.setName("ShenZiping"); BeanUtils.copyProperties(p2, p1); System.out.println("test3"+p2.getAge()); System.out.println("test3"+p2.getName()); } public static void test4() throws Exception{ Person person = new Person(); Man man = new Man(); person.setName("ShenZiping"); BeanUtils.copyProperties(man, person); System.out.println("test4"+man.getName()); } public static void myConvertTest(){ ConvertUtils.register(new Converter(){ public Object convert(Class clazz, Object value){ if(clazz==Date.class){ SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); try{ return dateFormat.parse((String)value); }catch(ParseException e){ throw new RuntimeException("invalid format"); } } return null; } }, Date.class); Date date = (Date)ConvertUtils.convert("2010-01-15",Date.class); System.out.println("myConvertTest"+date); } }
|