package com.teenyda.动态代理;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
public class Demo2 {
public static void main(String[] args) {
// TODO Auto-generated method stub
ILogin user = new Usre();
InvocationHandler handler = new UserHandler(user);
Class<?> clazz = user.getClass();
ILogin u = (ILogin)Proxy.newProxyInstance(clazz.getClassLoader(), clazz.getInterfaces(), handler);
u.login("张三");
u.killBoss("张三");
}
}
//接口
interface ILogin{
void login(String name);
void killBoss(String name);
void update(String name);
}
//被代理类
class Usre implements ILogin{
@Override
public void login(String name) {
// TODO Auto-generated method stub
System.out.println(name+"登录啦!");
}
@Override
public void killBoss(String name) {
// TODO Auto-generated method stub
System.out.println(name+"击杀boss啦!");
}
@Override
public void update(String name) {
// TODO Auto-generated method stub
System.out.println(name+"升级啦!");
}
}
//代理类
class UserHandler implements InvocationHandler{
private Object obj;
public UserHandler(Object obj) {
this.obj = obj;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.print("log:");
method.invoke(obj, args);
System.out.println("正在记录!");
return args;
}
}