一:UserService.java
package com.cloud.demo6; public interface UserService { void querUsers(); void saveUser(); void deleteUser(); } |
二:UserServiceImpl.java
package com.cloud.demo6;
public class UserServiceImpl implements UserService{
@Override
public void querUsers() {
System.out.println("UserServiceImpl.querUsers()");
}
@Override
public void saveUser() {
System.out.println("UserServiceImpl.saveUser()");
}
@Override
public void deleteUser() {
System.out.println("UserServiceImpl.deleteUser()");
}
}
三:LogJdkProxy.java
package com.cloud.demo6;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
public class LogJdkProxy implements InvocationHandler{
private Object target;
public LogJdkProxy(Object target){
this.target=target;
}
/**
* 创建代理对象
* @return
*/
public Object createProxyInstance(){
return Proxy.newProxyInstance(getClass().getClassLoader(), target.getClass().getInterfaces(), this);
}
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
System.out.println("操作前");
//执行原始对象方法
Object result=method.invoke(target, args);
System.out.println("操作后");
return result;
}
}
四:MainTest.java
package com.cloud.demo6;
import org.junit.Test;
public class MainTest {
@Test
public void test1() throws Exception {
UserService userService=new UserServiceImpl();
userService=(UserService) new LogJdkProxy(userService).createProxyInstance();
userService.querUsers();
}
}