接口:
public interface People {
void weekDay();
}
实现类:
public class Student implements People{
@Override
public void weekDay() {
System.out.println("上学");
}
}
测试方法:
public static void main(String[] args) {
final Student stu = new Student();
/**
* ClassLoader.getSystemClassLoader()类加载器
* stu.getClass().getInterfaces() 或new Class[]{People.class}需要实现的接口
* InvocationHandler回调方法
*/
People p = (People) Proxy.newProxyInstance(ClassLoader.getSystemClassLoader(),
stu.getClass().getInterfaces(),
new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args)throws Throwable {
System.out.println("喝牛奶");
Object o =method.invoke(stu, args);
System.out.println("回家");
return o;
}
});
p.weekDay();
}