Bean工厂
package com.test;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
/**
* Bean工厂
*/
public class BeanFactory {
/**
* 创建实例
*
* @param clazz
* @return
*/
public static Object newInstance(Class<?> clazz) {
Object instance;
try {
instance = clazz.newInstance();
} catch (Exception e) {
throw new RuntimeException(e);
}
return instance;
}
/**
* 方法调用
*
* @param obj
* @param method
* @param args
* @return
*/
public static Object invokeMethod(Object obj, Method method, Object... args) {
Object result;
try {
method.setAccessible(true);
result = method.invoke(obj, args);
} catch (Exception e) {
throw new RuntimeException(e);
}
return result;
}
/**
* 设置成员变量值
*
* @param obj
* @param field
* @param value
*/
public static void setField(Object obj, Field field, Object value) {
try {
field.setAccessible(true);
field.set(obj, value);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
- method.setAccessible(true);
- field.setAccessible(true);
使私有的成员和方法可以访问
测试
package com.test;
public class Student {
private int id;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
}
package com.test;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
public class Test {
public static void main(String[] args) throws ClassNotFoundException, IllegalArgumentException, IllegalAccessException {
Class cl = Class.forName("com.test.Student");
//获得Student类的类类型
//通过类类型创建Student类的实例
Student student= (Student) BeanFactory.newInstance(cl);
//获得类中定义的属性
Field[] beanFields = cl.getDeclaredFields();
//遍历属性
for (Field beanField : beanFields) {
//设置属性,依赖注入的影子
BeanFactory.setField(student, beanField, Integer(1));
}
System.out.println(student.getId());
//
// BeanFactory.setField(student, "name", "king");
}
private static Object Integer(int i) {
// TODO Auto-generated method stub
return i;
}
}