接口类
public interface Users {
String login(String loginName,int password);
void deleteByID(int i);
String query();
}
接口实现类
public class UserService implements Users{
@Override
public String login(String loginName, int password) {
String rs = "LoginName or the password incorrect";
if ("admin".equals(loginName) && 1234== password)
rs = "Login succeed.";
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return rs;
}
@Override
public void deleteByID(int i) {
System.out.println("Removing User with ID["+i+"] right now~~~");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
@Override
public String query() {
String rs = "Find out 1000 users match";
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return rs;
}
}
代理创建类
import java.lang.reflect.Proxy;
public class UserCenterProxy {
public static <T>T getProxy(T us) {
return (T) Proxy.newProxyInstance(us.getClass().getClassLoader(),
us.getClass().getInterfaces(),
(proxy, method, args) -> {
long startTime = System.currentTimeMillis();
Object rs = method.invoke(us, args);
if (rs != null) System.out.println(rs);
long endTime = System.currentTimeMillis();
System.out.println(method.getName() + " method's time usage is "
+ (endTime - startTime) / 1000.0 + "s");
return rs;
//这个返回值的作用没搞明白,总之返回值为method.invoke不会报NPE
});
}
}
测试执行体
public class TestDemo {
public static void main(String[] args) {
UserService us = new UserService();
Users u = UserCenterProxy.getProxy(us);
u.login("admin",1234);
u.query();
u.deleteByID(007);
}
}