Java中的代理

来源:互联网 发布:广告牌生成器软件 编辑:程序博客网 时间:2024/05/18 23:55

1.先创建以DAO层接口
package cn.ouyang.test.entity;
//DAO层接口
public interface Student {
 public void  deleteById(intid);
 
 public void  selectById(intid);
 
}

2.为之前接口写实现类
package cn.ouyang.test.entity;

public class StudentImpl implementsStudent {

@Override
 public void deleteById(int id) {
  System.out.println("进行删除...");
 }

@Override
 public void selectById(int id) {
  System.out.println("进行查询...");
 }

}
3.写代理类:(动态代理):
package cn.ouyang.test.entity;

importjava.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class Inction implementsInvocationHandler {
 Object terget=null;
 public Inction(Object obj){
  this.terget=obj;
 }

@Override
 public Object invoke(Object proxy, Method method,Object[] args)
   throwsThrowable {
  log();
  Objectresult=method.invoke(terget, args);
  return result;
 }
 public void log(){
  System.out.println("正在记录日志!");
 }
 
 public Object getProxy(){
  returnProxy.newProxyInstance(terget.getClass().getClassLoader(),terget.getClass().getInterfaces(), this);
 }

}
4.写测试类:
package cn.ouyang.test.test;

importcn.ouyang.test.entity.Inction;
import cn.ouyang.test.entity.Student;
import cn.ouyang.test.entity.StudentImpl;

public class Test {


 public static void main(String[] args) {
  //得到真实对象
  Student student=newStudentImpl();
  //代理对象
  Inction inction=newInction(student);
  Studentstudent2=(Student)inction.getProxy();
  student2.selectById(2);
  student2.deleteById(2);
 }

}

 

0 0
原创粉丝点击