- import java.beans.IntrospectionException;
- import java.beans.PropertyDescriptor;
- import java.lang.reflect.Constructor;
- import java.lang.reflect.InvocationTargetException;
- import java.lang.reflect.Method;
- class Person{
- private String name;
- public Integer age;
- public Person(){
-
- }
- public Person(String name,Integer age){
- this.name=name;
- this.age=age;
-
- }
- public void setName(String name) {
- this.name = name;
- }
- public String getName() {
- return name;
- }
- public void setAge(Integer age) {
- this.age = age;
- }
- public int getAge() {
- return age;
- }
- }
- public class JavaBeanTest{
- public static void main(String[]args){
-
- Class clazz=Person.class;
- try {
-
- Person p=(Person) clazz.newInstance();
- p.setName("jay_ma");
-
- String propertyName="age";
- PropertyDescriptor pd=new PropertyDescriptor(propertyName,clazz);
-
- Method method=pd.getWriteMethod();
- method.invoke(p, new Integer(20));
-
- System.out.println("姓名:"+p.getName()+"年龄:"+p.getAge());
- } catch (InstantiationException e) {
-
- e.printStackTrace();
- } catch (IllegalAccessException e) {
-
- e.printStackTrace();
- } catch (IntrospectionException e) {
-
- e.printStackTrace();
- } catch (IllegalArgumentException e) {
-
- e.printStackTrace();
- } catch (InvocationTargetException e) {
-
- e.printStackTrace();
- }
- }
-
- }
复制代码 |
|