比如现在有一个接口及其实现类:
public interface StudentInterface {
void eat(String food);
void study();
}
public class Student implements StudentInterface{
public void study() {
System.out.println("学Java");
}
public void eat(String food) {
System.out.println("吃" + food);
}
}
student类实现了studentInterface接口的两个方法:一个eat和一个study。这是通常编写代码的方法。
现在需要对study方法进行修改,通过动态代理的方式可以无需修改student类就可以改变study方法。
通过JDK提供的一个Proxy.newProxyInstance()
创建一个代理对象:
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
public class test {
public static void main(String[] args) {
Student stu = new Student();
StudentInterface proxyStu = (StudentInterface) Proxy.newProxyInstance(
stu.getClass().getClassLoader(),
new Class[]{StudentInterface.class},
new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
if (method.getName().equals("study")) {
System.out.println("学python");
return null;
} else {
return method.invoke(stu, args);
}
}
}
);
proxyStu.study();
}
}
Proxy.newProxyInstance()有三个参数:
student类的ClassLoader
;- 需要实现的接口数组,至少需要传入一个接口进去;
InvocationHandler
实例;
动态代理是利用Java的反射机制,Proxy.newProxyInstance创建了一个代理对象,
当我们通过代理对象调用一个方法时候,这个方法的调用就会被转发到实现InvocationHandler接口类的invoke方法来调用。
proxy:代理类代理的真实代理对象
method:我们所要调用某个对象真实的方法的Method对象
args:指代代理对象方法传递的参数