【例 15.23]定义 MylnvocationHandler 的类
【例15.24】定义接口
【例15.25】定义真实主题实现类
【例15.26]测试动态代理
package file;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
//定义 Subject 接口
interface Subject
{
public String say(String name,int age); //定义抽象方法 say
}
interface Subject1
{
public String say1(String name);
}
//真实主题实现类
class RealSubject implements Subject,Subject1
{
public String say(String name, int age)
{
return "姓名:" + name +",年龄:"+ age;
}
public String say1(String name)
{
return "姓名:" + name;
}
}
class MyInvocationHandler implements InvocationHandler
{
private Object obj;//真实主题
public Object bind(Object obj)//绑定真实主题
{
this.obj = obj;
//取得代理对象
return Proxy.newProxyInstance(obj.getClass().getClassLoader(),obj.getClass().getInterfaces(), this);
}
//动态调用方法
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable
{
Object temp =method.invoke(this.obj,args);//调用方法,传入真实主题和参数
return temp;//返回方法的返回信息
}
}
public class demo
{
public static void main(String[] args) throws Exception
{
//实例化代理操作类
MyInvocationHandler handler = new MyInvocationHandler();
//绑定真实对象
Subject sub = (Subject) handler.bind(new RealSubject());
Subject1 sub1 = (Subject1) handler.bind(new RealSubject());
//通过动态代理调用方法
String info = sub.say("李四", 22);
String info1 = sub1.say1("zhangsan");
System.out.println(info);
System.out.println(info1);
}
}