2011/12/5
原来spring中用到了java的反射机制,研究了下java的反射机制发现静态代理中的method.invoke(sub, args);也是用动态代理实现的。
?
将用反射机制实例化的类:
?
反射机制的代码:
public class ReflectTest {/** * @param args * @throws NoSuchMethodException * @throws SecurityException */public static Car initByDefaultConst() throws Exception {ClassLoader loader = Thread.currentThread().getContextClassLoader();Class clazz = loader.loadClass("org.model.Car");Constructor cons = clazz.getDeclaredConstructor(null);//获取构造函数Car car = (Car) cons.newInstance(); 实例化Method setBrand = clazz.getMethod("setBrand", String.class); //获取类中方法setBrand.invoke(car, "CA72");调用方法Method setColor = clazz.getMethod("setColor", String.class);setColor.invoke(car, "黑色");Method setMaxSpeed = clazz.getMethod("setMaxSpeed", int.class);setMaxSpeed.invoke(car, 200);return car;}@SuppressWarnings("unchecked")public static void main(String[] args) {// TODO Auto-generated method stubtry {Car car = ReflectTest.initByDefaultConst();car.introduce();} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}}}?