最近回顾了一下反射,写了个简单的代理
一、测试类
package com.zhou.test;
import java.lang.reflect.Proxy;
public class TestProxy {
public static void main(String[] args) {
//必须用接口
StudentDao studentDao = new StudentDaoImpl();
//在主方法前或者后添加通用的方法的实现
MyInvockHandler myInvockHandler = new MyInvockHandler(studentDao);
//返回的代理对象就是上面的接口对象,但是不一样
StudentDao p = (StudentDao) Proxy.newProxyInstance(studentDao.getClass().getClassLoader(), studentDao.getClass().getInterfaces(), myInvockHandler);
p.login();
p.regist();
}
}
二、接口
package com.zhou.test;
public interface StudentDao {
public void login();
public void regist();
}
三、接口的实现
package com.zhou.test;
public class StudentDaoImpl implements StudentDao {
@Override
public void login() {
System.out.println("登录");
}
@Override
public void regist() {
System.out.println("注册");
}
}
四、代理需要做的事情
package com.zhou.test;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
public class MyInvockHandler implements InvocationHandler{
private Object target;//接口对象
public MyInvockHandler(Object target) {
this.target = target;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args)throws Throwable {
System.out.println("woxianzuo ");
//应用反射的方法调用方法执行
Object result = method.invoke(target, args);
System.out.print("wohouzuo");
return result;//返回代理对象
}
}