1 目标类接口
package com.cgm.invokeclass;
public interface ITeacher {
public void talk();
}
2.目标类
package com.cgm.invokeclass;
public class Teacher implements ITeacher{
int num=0;
public Teacher(int num){this.num=num;}
public void talk(){
System.out.println("laoshi zai jiang"+num);
}
}
3代理类
package com.cgm.invokeclass;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
public class ProxyDemo {
public static void main(String[] args) throws Exception {
final Object o=new Teacher(1); //代理对象的加载器
Object proxyObj=Proxy.newProxyInstance(ProxyDemo.class.getClassLoader(),
//ITeacher.class.getClasses(),
//目标类的接口
new Class[]{ITeacher.class},
//句柄 用户的每一次调用都能拦截到她的方法
new InvocationHandler() { //匿名内部类
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
System.out.println("你执行的方法是"+method.getName());
Object oValue=method.invoke(o, args);
return oValue;
}
});
ITeacher itacher=(ITeacher) proxyObj;
itacher.talk();
String ss=itacher.toString();
System.out.println("o========="+o);
System.out.println("ss========="+ss); //com.cgm.invokeclass.Teacher@a83b8a
System.out.println("ss========="+itacher.getClass()); //$Proxy0 动态代理类
}
}
结构见图:
目标类接口(父类)
/ \
/ \
目标类(子类) 代理类(内存生成子类的代理对象)
package com.cgm.invokeclass;
public interface ITeacher {
public void talk();
}
2.目标类
package com.cgm.invokeclass;
public class Teacher implements ITeacher{
int num=0;
public Teacher(int num){this.num=num;}
public void talk(){
System.out.println("laoshi zai jiang"+num);
}
}
3代理类
package com.cgm.invokeclass;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
public class ProxyDemo {
public static void main(String[] args) throws Exception {
final Object o=new Teacher(1); //代理对象的加载器
Object proxyObj=Proxy.newProxyInstance(ProxyDemo.class.getClassLoader(),
//ITeacher.class.getClasses(),
//目标类的接口
new Class[]{ITeacher.class},
//句柄 用户的每一次调用都能拦截到她的方法
new InvocationHandler() { //匿名内部类
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
System.out.println("你执行的方法是"+method.getName());
Object oValue=method.invoke(o, args);
return oValue;
}
});
ITeacher itacher=(ITeacher) proxyObj;
itacher.talk();
String ss=itacher.toString();
System.out.println("o========="+o);
System.out.println("ss========="+ss); //com.cgm.invokeclass.Teacher@a83b8a
System.out.println("ss========="+itacher.getClass()); //$Proxy0 动态代理类
}
}
结构见图:
目标类接口(父类)
/ \
/ \
目标类(子类) 代理类(内存生成子类的代理对象)