public interface Person {
void eat();
}
public class Student implements Person {
@Override
public void eat() {
System.out.println("吃饭");
}
}
public class PersonProxy implements InvocationHandler{
private Person p;
public PersonProxy(Person obj){
this.p=obj;
}
@Override
public Person invoke(Object proxy, Method method, Object[] args) throws Throwable {
if(method.getName().equals("eat")){
System.out.println("代理测试");
}
return (Person) method.invoke(p, args);
}
public Object getProxy(){
return Proxy.newProxyInstance(p.getClass().getClassLoader(), p.getClass().getInterfaces(), this);
}
}
public class Mytest {
public static void main(String[] args) {
Person p=(Person) new PersonProxy(new Student()).getProxy();
p.eat();
//这里会报类型转换错误
Student st=(Student) new PersonProxy(new Student()).getProxy();
st.eat();
}
}
想知道为啥我传的是Student对象,为哈转Student调用eat()方法会报类型转换异常?转Person就不会有异常!