public class DY {
public static void main(String[] args) {
MyHandler myHandler = new MyHandler();
Bird bird = (Bird) Proxy.newProxyInstance(Bird.class.getClassLoader(), new Class[]{Bird.class}, myHandler);
System.out.println(bird.getClass().getName());
bird.fly();
}
static class MyHandler implements InvocationHandler {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("time ------> ");
return null;
}
}
interface Bird {
void fly();
}
}
我打印了 bird
的 classname
输出如下:com.example.pdog.dy.$Proxy0
为什么可以强转成Bird
?
Proxy.newProxyInstance方法的第二个参数是代理生成的类需要实现的接口,
你的参数为new Class[]{Bird.class}, newProxyInstance出来的对象实现了Bird接口
所以可以强转为Bird,如果你的参数为new Class[]{Tiger.class} 就不能转为Bird
说的有点拗口