繁体   English   中英

通过反射将子类类型传递给Java泛型方法不会引发异常

[英]Passing Subclass Type to Java Generic Method with reflection throws no Exception

因此,我在Spring中遇到一个奇怪的错误,在该错误中,调用了抽象控制器方法并传递了类型系统不应该允许的对象。

这是一个演示该错误的简单示例。

import org.junit.Test;

import java.lang.reflect.InvocationTargetException;

public class RandomJavaTesting
{
    public static class Animal {
    }

    public static class Cat extends Animal {
    }

    public static class AnimalManager<T extends Animal> {

        // This gets called and doesn't blow up
        public void add(T animal){
            // This will throw a class cast exception
            // Why does this blow up here for CatManager?
            this.callAdd(animal);
        }

        public void callAdd(T animal){

        }
    }

    public static class CatManager extends AnimalManager<Cat> {

        @Override
        public void callAdd(Cat animal)
        {
            // This will never run
        }
    }


    @Test
    public void callingGenericMethodWithSubClassType() throws InvocationTargetException, IllegalAccessException
    {

        CatManager manager = new CatManager();
        Animal animal = new Animal();
        AnimalManager.class.getDeclaredMethod("add", Animal.class).invoke(manager, animal);

    }
}

此测试给出以下异常:

java.lang.reflect.InvocationTargetException
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:498)
        at RandomJavaTesting.callingGenericMethodWithSubClassType(RandomJavaTesting.java:44)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:498)
        at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
        at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
        at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
        at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
        at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
        at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
        at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
        at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
        at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
        at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
        at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
        at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
        at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
        at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
        at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:117)
        at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:42)
        at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:262)
        at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:84)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:498)
        at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)
Caused by: java.lang.ClassCastException: RandomJavaTesting$Animal cannot be cast to RandomJavaTesting$Cat
        at RandomJavaTesting$CatManager.callAdd(RandomJavaTesting.java:28)
        at RandomJavaTesting$AnimalManager.add(RandomJavaTesting.java:20)
        ... 32 more

基本上,我的问题是,为什么调用add方法不会导致ClassCastException。 为什么调用callAdd会导致异常? 我知道一般信息不会在运行时保留,但是我假设扩展类会导致保留一般类的类型参数。 这是Guava TypeToken背后的机制。 或者,至少那是我的想法。

基本上,它违反了里斯科夫的替代原则。

对于add方法,可以将T类型视为Animal,但是对于addAll方法,将类型指定为Cat,因此您不能将Cat类型替换为Animal类型。

正确的是保留了泛型超级类型,但您高估了含义。 它仅意味着反射方法(如Class.getGenericSuperclass()将为您提供信息,而这实际上是Guava TypeToken背后的机制。

继承的方法仍需进行类型擦除。 顺便说一句,如果将错误类型的对象传递给Method.invoke ,则不会得到ClassCastException ,而会得到IllegalArgumentException 但是,当然,如果您对方法AnimalManager.class.getDeclaredMethod("add", Animal.class)执行反射查询,并最终获得具有除add(Animal)以外的签名的方法,那将会造成混乱。

这甚至适用于您覆盖该方法的情况,例如,当您使用AnimalManager.class.getDeclaredMethod("callAdd", Animal.class).invoke(manager, animal); ,您仍然没有得到IllegalArgumentException ,而是调用了方法addAll(Animal) ,当尝试将其委​​托给显式定义的方法addAll(Cat)时,该方法将产生ClassCastException 此过程中涉及的addAll(Animal)方法称为bridge方法

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM