1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
| public class JDK { public static void main(String[] args) { Class[] interfaces = {UserDao.class}; UserDaoImpl userDao = new UserDaoImpl(); UserDao proxyInstance = (UserDao)Proxy.newProxyInstance(JDK.class.getClassLoader(), interfaces, new UserDaoProxy(userDao));
proxyInstance.add(1, 2); } }
interface UserDao{ public abstract int add(int a, int b);
public abstract String update(String id); }
class UserDaoImpl implements UserDao {
@Override public int add(int a, int b) { return a + b; }
@Override public String update(String id) { return id; } }
class UserDaoProxy implements InvocationHandler { private Object obj; public UserDaoProxy(Object obj){ this.obj = obj; };
@Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { System.out.println("方法之前执行:" + method.getName()); System.out.println("传递的参数" + Arrays.toString(args));
Object res = method.invoke(obj, args);
System.out.println("方法之后执行:" + res);
return res; } }
|