由于spring中的ioc和aop编程 也就是我们经常说的切面编程 里面用到了反射和动态代理,和cglib代理,下面的代码简单实现了一下
1.编写一个接口
package com.liangxin;
public interface Subject {
public void rent();
public void hello(String str);
}
2.书写一个真实的对象并且要实现这个接口
package com.liangxin;
/**
* Created by Enzo Cotter on 2019/5/3.
*/
public class RealSubject implements Subject {
@Override
public void rent() {
System.out.println(" i want to rent my house");
}
@Override
public void hello(String str) {
System.out.println("hell0"+ str);
}
}
3.创建代理对象 实现这个接口 (实现同一个接口)
package com.liangxin;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
/**
*/
public class DynamicProxy implements InvocationHandler {
// 这个使我们要代理的真实
private Object subject;
//构造方法,给我们要代理的对象赋初值
public DynamicProxy(Object subject) {
this.subject = subject;
}
;
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
//在代理真是对象钱我们可以增加我们自己的一些操作
// 在代理真实对象前我们可以添加一些自己的操作
System.out.println("before rent house");
System.out.println("Method:" + method);
// 当代理对象调用真实的方法是,会自动跳转到代理对象关联的handler对象的invoke方法调用
method.invoke(subject, args);
// 在代理真实对象后我们也可以添加自己的一些操作
System.out.println("after rent house");
return null;
}
}
4.测试类
package com.liangxin;
import com.liangxin.DynamicProxy;
import com.liangxin.RealSubject;
import com.liangxin.Subject;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy;
public class Client {
public static void main(String[] args) {
// 我们要代理的真实对象
Subject realSubject = new RealSubject();
// 我们要代理哪个真实对象,就将该对象传进去,最后是通过该真实对象来调用其方法的
InvocationHandler handler = new DynamicProxy(realSubject);
/*
* 通过Proxy的newProxyInstance方法来创建我们的代理对象,我们来看看其三个参数
* 第一个参数 handler.getClass().getClassLoader() ,我们这里使用handler这个类的ClassLoader对象来加载我们的代理对象
* 第二个参数realSubject.getClass().getInterfaces(),我们这里为代理对象提供的接口是真实对象所实行的接口,表示我要代理的是该真实对象,这样我就能调用这组接口中的方法了
* 第三个参数handler, 我们这里将这个代理对象关联到了上方的 InvocationHandler 这个对象上
*/
Subject subject = (Subject) Proxy.newProxyInstance(handler.getClass().getClassLoader(), realSubject
.getClass().getInterfaces(), handler);
System.out.println(subject.getClass().getName());
subject.rent();
subject.hello("world");
}
}