1. 欲代理的类必须实现某个接口,若不实现接口则会报以下异常
具体测试代码
package com.kevin;import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;/**
* Created by liukai on 17/8/13.
*/
public class DynaProxy {
public static void main(String []args){
PersonProxy proxy= new PersonProxy(new Kevin());
//直接生成类而非接口
Kevin kevin = (Kevin)Proxy.newProxyInstance(DynaProxy.class.getClassLoader(),new Class[]{Kevin.class},proxy);
kevin.sleep();
}
}
class Kevin {
public void sleep(){
System.out.println("小明在睡觉");
}
}
class PersonProxy implements InvocationHandler {
Kevin obj = null;
public PersonProxy(Kevin kevin){//直接代理类,而非接口
obj = kevin;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("小明在脱衣服");
method.invoke(obj,args);
System.out.println("小明在穿衣服");
return null;
}
}
修改以上代码
package com.kevin;import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;/**
* Created by liukai on 17/8/13.
*/
public class DynaProxy {
public static void main(String []args){
PersonProxy proxy= new PersonProxy(new Kevin());
//生成代理接口 生成的对象必须用接口声明,并且只能转换为new Class[]{Person.class}中包含的接口
Person kevin = (Person)Proxy.newProxyInstance(DynaProxy.class.getClassLoader(),new Class[]{Person.class},proxy);//new Class[]{Person.class中必须是接口的class对象,不可以是类的class对象,否则会报对象不是接口
//Person kevin = (Person)Proxy.newProxyInstance(DynaProxy.class.getClassLoader(),Kevin.class.getInterfaces(),proxy);
kevin.sleep();
}
}
interface Person{
void sleep();
}
class Kevin implements Person{
public void sleep(){
System.out.println("小明在睡觉");
}
}
class PersonProxy implements InvocationHandler {
Person obj = null;
public PersonProxy(Person kevin){//直接代理类,而非接口
obj = kevin;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("小明在脱衣服");
method.invoke(obj,args);
System.out.println("小明在穿衣服");
return null;
}
}
所以一个类若未实现接口是无法使用jdk动态代理的