- 获取类
Class<?> perClazz = Class.forName("reflect.Person");
System.out.println("perClazz: " + perClazz);
Class<?> perClazz1 = Person.class;
System.out.println("perClazz1: " + perClazz1);
Person per = new Person();
Class<?> perClazz3 = per.getClass();
System.out.println("perClazz3: " + perClazz3);
- 获取类中的参数
//获取自己以及父类的public参数
Field[] fields = clazz.getFields();
for (Field f : fields) {
System.out.println(f);
}
//获取自己的所有参数
Field[] fieldsDeclared = clazz.getDeclaredFields();
for (Field f : fieldsDeclared) {
System.out.println(f);
}
- 获取类中的方法
// 本类和父类中的public的方法(包括public/private/protect 返回类型 函数全名)
Method[] methods = perClazz.getMethods();
for (Method m : methods) {
System.out.println(m);
}
//获取自己所有的方法
Method[] methods = clazz.getDeclaredMethods();
for (Method m : methods) {
System.out.println(m);
}
- 获取构造函数
/*
* 包装类和基本属性不一样
*
* 传入参数类型
* 传入参数,用构造函数实例化对象
*
* */
Constructor constructor = clazz.getConstructor(int.class);
Object o = constructor.newInstance(1234);
Person per = (Person)o;
- 实例化对选
//创建一个对象
Person p = (Person) clazz.newInstance();
p.interfaceMethod();
/*
* 包装类和基本属性不一样
*
* 传入参数类型 传入参数,用构造函数实例化对象
*
*/
//没有传入参数就写null
Constructor constructor = clazz.getConstructor(int.class);
Object o = constructor.newInstance(1234);
Person per = (Person) o;
System.out.println(per.getId());
//获取配置文件
Properties prop = new Properties();
prop.load(new FileReader("class.txt"));
String classname = prop.getProperty("classname");
String methodname = prop.getProperty("methodname");
/*
* classname=reflect.Student
* methodname=sayHi
*/
Class<?> perClazz = Class.forName(classname);
method = perClazz.getMethod(methodname);
//用制定的对象执行该方法
method.invoke(perClazz.newInstance());
- 万能get set方法
public class PropertyUtil {
public static void setProperty(Object obj, String propertyName, Object value) throws Exception{
Class clazz = obj.getClass();
Field field = clazz.getDeclaredField(propertyName);
field.setAccessible(true);
field.set(obj, value);
}
public static Object getProperty(Object obj, String propertyName) throws Exception {
Class clazz = obj.getClass();
Field field = clazz.getDeclaredField(propertyName);
field.setAccessible(true);
Object o = field.get(obj);
return o;
}
}
//==================================================================
执行方法
//==================================================================
Person person = new Person();
PropertyUtil.setProperty(person, "id", 222);
System.out.println(person.getId());
PropertyUtil.setProperty(person, "name", "mk");
Object obj = PropertyUtil.getProperty(person, "name");
System.out.println(obj);
- 测试
ArrayList<Integer> list = new ArrayList<>();
list.add(123);
list.add(321);
Class listClazz = list.getClass();
method = listClazz.getMethod("add", Object.class);
method.invoke(list, "lalala");
System.out.println(list);
网友评论