为什么Java允许将代理类检查转换为声明类型而不是泛型类型?

时间:2015-07-08 15:26:16

标签: java generics casting proxy

相当简单的问题......

private static <R extends Runnable> void test(R r, Class<R> rClass) {
    //Assume invocation handlers ih1, ih2, ih3 already declared

    //Example 1: Checked-cast to declared type specified as interface
    Runnable x = (Runnable) Proxy.newProxyInstance(Runnable.class.getClassLoader(), new Class[]{Runnable.class}, ih1); //No warning

    //Example 2: Checked-cast to declared type not specified as interface
    String y = (String) Proxy.newProxyInstance(Runnable.class.getClassLoader(), new Class[]{Runnable.class}, ih2); //No warning at compile-time, even though String does not implement Runnable (I would imagine this would fail at runtime, although I haven't tried it)

    //Example 3: Cast to generic type
    R z = (R) Proxy.newProxyInstance(rClass, new Class[]{rClass}, ih3); //Unchecked cast warning
}

Proxy.newProxyInstance返回一个类型为Object的对象,因此似乎有一些神奇的东西告诉编译器将此对象转换为任何声明的类型是安全的。这对我来说没有意义(即使代理类的JavaDoc只能说代理可以安全地转换为它自己的一种接口类型)并导致一些奇怪的行为,如上面的例子2所示。然而,这同样的魔法&#34;对于泛型类型没有相同的安全结果。

如果你想代理一个泛型类型,除了&#34;抑制警告&#34;有什么方法吗?

0 个答案:

没有答案