Java中的代理

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

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

public class StudentImpl implements Student {

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

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

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

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

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

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

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

import cn.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=new StudentImpl();
  //代理对象
  Inction inction=new Inction(student);
  Student student2=(Student)inction.getProxy();
  student2.selectById(2);
  student2.deleteById(2);
 }

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值