package com.edu;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
public class ProxyUtil {
public static UserService getProxy(UserService userService) {
return (UserService) Proxy.newProxyInstance(userService.getClass().getClassLoader(),
userService.getClass().getInterfaces(), new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
long startTimer = System.currentTimeMillis();
Object o = method.invoke(userService, args);
long endTimer = System.currentTimeMillis();
System.out.println(method.getName()+"耗时:"+(endTimer-startTimer)/1000.0+"秒");
return o;
}
});
}
}
package com.edu;
public class test1 {
public static void main(String[] args) {
UserService service =ProxyUtil.getProxy(new UserServiceImpl()) ;
System.out.println(service.userLogin("admin", "123456"));
service.selectUsers();
System.out.println(service.deleteUsers());
}
}
package com.edu;
public interface UserService {
String userLogin(String username,String password);
void selectUsers();
boolean deleteUsers();
}
package com.edu;
public class UserServiceImpl implements UserService {
@Override
public String userLogin(String username, String password) {
try {
if ("admin".equals(username) && "123456".equals(password)) {
Thread.sleep(3000);
return "success";
}
return "用户名或密码错误";
} catch (Exception e) {
e.printStackTrace();
return "error";
}
}
@Override
public void selectUsers() {
System.out.println("查询100个用户数据成功");
try {
Thread.sleep(100);
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public boolean deleteUsers() {
System.out.println("删除100个用户数据成功");
try {
Thread.sleep(1000);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
}