1先写一个需要代理的类,把主要功能写进去
package com.zpf.Service;
public class BigStar implements Star {
String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public BigStar(String name) {
this.name = name;
}
public BigStar() {
}
/**
*
* @param name 歌名
* @return
*/
public String sing(String name){
System.out.println(this.name+"正在唱歌");
return "谢谢,谢谢";
}
public void dance(){
System.out.println(this.name+"正在跳舞");
}
}
2 把该类的方法写到接口里
package com.zpf.Service;
public interface Star {
String sing(String name);
void dance();
}
3.创建代理类
package com.zpf.Service;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
public class ProxyUtil {
/**
* bigStar传入需要代理的对象
*
* @param
* @return
*/
public static Star createProxy1(final BigStar bigStar) {
/* newProxyInstance(ClassLoader loader,用于指定一个类加载啊器
Class<?>[] interfaces,指定生成的代理长什么样子
InvocationHandler h)用来指定生成的代理对象要干什么事情*/
Star starproxy = (Star) Proxy.newProxyInstance(ProxyUtil.class.getClassLoader(), new Class[]{Star.class}, new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
if (method.getName().equals("sing")) {
System.out.println("20万");
} else if (method.getName().equals("dance")) {
System.out.println("准备场地,1000万");
}
return method.invoke(bigStar, args);
}
});
return starproxy;
}
/**
* 需要被代理的对象
* @param userService
* @return
*/
public static UserService createProxyUser(final UserServiceImpl userService) {//写一个静态方法作为工具类
/* ClassLoader loader,
Class<?>[] interfaces,
InvocationHandler h*/
/**
*
*/
UserService userServiceProxy = (UserService) Proxy.newProxyInstance(ProxyUtil.class.getClassLoader(), new Class[]{UserService.class}, new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
if (method.getName().equals("login")||method.getName().equals("deleteUsers")||method.getName().equals("selectUser")) {
System.out.println("执行前");
Object invoke = method.invoke(userService, args);
System.out.println("执行后");
return proxy;
}else {
Object invoke = method.invoke(userService, args);
return invoke;
}
}
});
return userServiceProxy;
}
}
4.写测试方法
package com.zpf;
import com.zpf.Service.*;
import org.junit.Test;
public class testProxy {
@Test
public void testSing() {
BigStar s = new BigStar("陈奕迅");
Star starProxy = ProxyUtil.createProxy1(s);
String xiexie = starProxy.sing("富士山下");
System.out.println(xiexie);
starProxy.dance();
}
@Test
public void testProxyUser() throws Exception {
UserServiceImpl u = new UserServiceImpl();//创建需要代理的对象
UserService userServiceProxy = ProxyUtil.createProxyUser(u);//用代理类的方法创建代理对象
String[] strings = userServiceProxy.selectUser();//代理对象调用方法
System.out.println(strings);
}
}