1.被代理类和接口
public interface Person{
void saySomething(String msg);
}
public class Student implements Person{
public void saySomething(String msg){
System.out.println(msg);
}
}
2. 实现InvocationHandler的代理类
public class Emcee implements InvocationHandler
{
private Person student;
public Emcee(Person student)
{
this.student = student;
}
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable
{
System.out.println("有请下一位");
method.invoke(this.student,args);
System.out.println("谢谢这位同学的精彩演讲");
return null;
}
}
3. 实现
public class Stage
{
public static void main(String[] args)
{
Person student = new Student();
Class<?> classType = student.getClass();
InvocationHandler handler = new Emcee(student);
Person studentProxy = (Person)Proxy.newProxyInstance(
classType.getClassLoader(),
classType.getInterfaces(),
handler
);
studentProxy.saySomething("主持人好2啊!");
}
}
注意import相应的包
java.lang.reflect.*