欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

JDK代理模式 博客分类: java  

程序员文章站 2024-03-22 10:03:22
...
第一个类:jobService
package com.my.proxy;

public interface JobService {

//显示所有员工
public void showAllEmplayee();

}

第二个类:jobServiceImpl
package com.my.proxy;

public class JobServiceImpl implements JobService {

private int type;
private String jobName;

public JobServiceImpl(String jobName,int type){
this.jobName = jobName;
this.type = type;
}

@Override
public void showAllEmplayee() {
System.out.println("当前登录用户为:"+jobName+",有权限查看职员列表和添删改操作!");

}

}

第三个类:JdkProxy
package com.my.proxy;

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

/**
* 使用jdk的动态代理
* @author mengyao
*
*/
public class JdkProxy implements InvocationHandler{

private Object obj;

//通过jdk代理方式调用
public Object getProxy(Object obj){
this.obj = obj;
//获取代理对象,注意这里的三个参数分别代表:1代理类的类装载器,2代理类必须实现接口后的所有接口,3回调函数
return Proxy.newProxyInstance(obj.getClass().getClassLoader(), obj.getClass().getInterfaces(), this);
}

@Override
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
Object result = method.invoke(obj, args);
return result;
}

}

第四个类:Junit测试类
package com.my.proxy;

import org.junit.BeforeClass;
import org.junit.Test;

public class JunitProxyTest {

@BeforeClass
public static void setUpBeforeClass() throws Exception {

}

@Test
public void test(){
JdkProxy proxy = new JdkProxy();
int type = 1;//1为领导,否则为职员
if (type == 1) {
JobService jobService = (JobService) proxy.getProxy(new JobServiceImpl("技术总监",1));
jobService.showAllEmplayee();
} else {
System.out.println("您的权限不足!");
}
}

}

以上代码复制可用