动态代理
第一步:实现钢笔接口
interface PenInterface {
void write();
void draw();
}
第二步:学生的手实现钢笔接口
public class StudentHand implements PenInterface {
@Override
public void write() {
System.out.println("学生用笔写字");
}
@Override
public void draw() {
System.out.println("学生用笔画画");
}
}
第三步:学生代理的功能
public class StudentProxy implements InvocationHandler {
private Object mTarget;
public StudentProxy(Object target) {
mTarget = target;
}
public Object getInstance() {
return Proxy.newProxyInstance(mTarget.getClass().getClassLoader(), mTarget.getClass().getInterfaces(), this);
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
doSthBefore();
Object object = method.invoke(mTarget, args);
doSthAfter();
return object;
}
private void doSthBefore() {
System.out.println("调用方法之前");
}
private void doSthAfter() {
System.out.println("调用方法之后");
}
}
最后:通过学生去动态实现相关功能
public static void main(String[] args) {
PenInterface penInterface = new StudentHand();
PenInterface student = (PenInterface) new StudentProxy(penInterface).getInstance();
student.draw();
//student.write();
}