所谓动态代理,即通过代理类Proxy的代理接口和实现类之间可以不直接发生联系,而可以在运行期实现动态关联
代理类要实现InvocationHandler接口的invoke方法
1、被代理类接口
public interface Student {
public String study();
}
2、被代理类
public class Scholar implements Student {
@Override
public String study() {
System.out.println("学习java");
return "项目有所进展";
}
}
3、代理类
public class MyInvocationHandler implements InvocationHandler {
Scholar scholar;
public MyInvocationHandler(Scholar scholar) {
super();
this.scholar = scholar;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
Object invoke = method.invoke(scholar, args);
return invoke;
}
}
4、测试类
public class Teacher {
public static void main(String[] args) {
Scholar scholar = new Scholar();
InvocationHandler invocationHandler = new MyInvocationHandler(scholar);
Student s = (Student)Proxy.newProxyInstance(Scholar.class.getClassLoader(),
Scholar.class.getInterfaces(), invocationHandler);
System.out.println(s.study());
}
}