1.先看一个例子,这是一个正常例子。
public class TestPorxt {
public static void main(String[] args) {
UserInterface user=new User();
UserInterface use=UserPorxy(user);
use.name("你好");
System.out.println(user.Getname()+"==="+use.Getname());
//System.out.println(user);
}
public static UserInterface UserPorxy(UserInterface user) {
UserInterface PUser=(UserInterface)Proxy.newProxyInstance(user.getClass().getClassLoader(),
user.getClass().getInterfaces(), new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
// TODO Auto-generated method stub
return method.invoke(user, args);
}
});
return PUser;
}
}
public class User implements UserInterface{
private String name;
@Override
public void name(String name) {
// TODO Auto-generated method stub
this.name=name;
System.out.println(name);
}
@Override
public String Getname() {
// TODO Auto-generated method stub
return name;
}
}
public interface UserInterface {
public void name(String name);
public String Getname();
}
2,为什么会报这个错:com.sun.proxy.$Proxy0 cannot be cast to 代理.User错误
我第一次写的时候直接给UserPorxy()这个方法中直接传入User对象,而java文档显示这个方法:为某个接口创建代理,所以传进去的必须是一个接口。