package com.itheima.base;
import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class RefelctDemo1 {
/**
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
// test1();
Class clazz = Class.forName("com.itheima.base.Person");
Person p = (Person) clazz.newInstance();//调用默认的构造方法
// Method writeMethod = clazz.getMethod("setUsername", String.class);
// writeMethod.invoke(p, "哈哈");
// System.out.println(p.getUsername());
Method method = clazz.getMethod("method1", String[].class);
method.invoke(p, (Object)new String[]{"a","b"});
method.invoke(p, new Object[]{new String[]{"a","b"}});
}
private static void test1() throws IntrospectionException,
IllegalAccessException, InvocationTargetException {
Person p=new Person();
PropertyDescriptor pd=new PropertyDescriptor("username", Person.class);
Method writeMethod = pd.getWriteMethod();
writeMethod.invoke(p, "护发素");//setusername
// System.out.println(p.getUsername());
Method readMethod = pd.getReadMethod();
Object invoke = readMethod.invoke(p, null);
System.out.println(invoke);
}
}
|
|