public class Main {
public static void main(String[] args) {
UserService userService = new UserServiceImpl();
InvocationHandler invocationHandler =
new UserInvocationHandler(userService);
UserService userService1 = (UserService)Proxy.newProxyInstance(
userService.getClass().getClassLoader(),
userService.getClass().getInterfaces(),
invocationHandler);
userService1.hello("hello");
}
}
public class UserInvocationHandler implements InvocationHandler {
private Object tageet;
public UserInvocationHandler() {
}
public UserInvocationHandler(Object tageet) {
this.tageet = tageet;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("before-----"+method.getName());
method.invoke(tageet,args);
System.out.println("after-----"+method.getName());
return null;
}
}
public interface UserService {
void hello(String str);
}
public class UserServiceImpl implements UserService {
@Override
public void hello(String name) {
System.out.println(name + " world");
}
}
运行结果:
before-----hello
hello world
after-----hello