JDKダイナミックエージェントdemo
1505 ワード
1、UserServiceクラスを作成します.
2実装クラスUserServiceImplの作成
3、試験類JDKProxyTest
public interface UserService {
public String getTheName(int id);
public Integer getTheAge(int id);
}
2実装クラスUserServiceImplの作成
public class UserServiceImpl implements UserService {
@Override
public String getTheName(int id) {
return " ";
}
@Override
public Integer getTheAge(int id) {
return 10;
}
}
3、試験類JDKProxyTest
public class JDKProxyTest implements InvocationHandler {
private Object target;
JDKProxyTest() {
super();
}
JDKProxyTest(Object target) {
super();
this.target = target;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("++++++ : " + method.getName() + "++++++");
Object result = method.invoke(target, args);
System.out.println("++++++ : " + method.getName() + "++++++"+result);
return result;
}
public static void main(String[] args) {
UserServiceImpl userService = new UserServiceImpl();
InvocationHandler handler=new JDKProxyTest(userService);
UserService userServiceProxy=
(UserService) Proxy.newProxyInstance(userService.getClass().getClassLoader(), userService.getClass().getInterfaces(), handler);
System.out.println(userServiceProxy.getTheName(1));
System.out.println(userServiceProxy.getTheAge(1));
}
}