简体   繁体   中英

Strange ClassCastException in java

I wrote some code as follow:

public class MyClass {
    public static void main(String[] args) {
        printIt(getLong());
        System.out.println("---------");
    }

    public static Object printIt(Object... objects) {
        System.out.println(objects[0].toString());
        return objects[0];
    }

    public static <T> T getLong() {
        return (T)Long.valueOf(1L);
    }
}

When I run it, it throws java.lang.ClassCastException as follow:

Exception in thread "main" java.lang.ClassCastException: java.lang.Long cannot be cast to [Ljava.lang.Object; at com.sealinetech.MyClass.main(MyClass.java:5)

But when I debug it with Evaluate Expression, It's OK Evaluate Expression is OK

My IDE is intellij , and the JDK version is jdk1.8.0_144

getLong method has generic return type. at compile time compiler decides call it with Object[] result type, because printIt accepts this argument type. in runtime compiler suggestion fails so you get this error: java.lang.Long cannot be cast to [Ljava.lang.Object

you can specify expected type with printIt(this.<Object>getLong()); (thanks to @CoderinoJavarino)

As already mentioned, the exception comes from the fact that the compiler resolves T to be Object[] rather than Object .

I get that this the code is just a toy example for something more complex. Depending on what the actual scenario is, an alternative solution to what has been already suggested is to constraint the return of type-parameter T to a non-array type of choice. In this trivial example perhaps it would be something like <T extends Number> .

However, it needs to be pointed out that only looking at the question code, it seems quite clear that given the name of the method, it is going to return Long or perhaps a long if null , is not a valid value, here it simply makes far more sense to get rid of the type-paramter T and set the return type as Long or long .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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