12

I have the following test class:

import java.io.Serializable;
public class Java8Problem {

    public void test(String stringArg) {
        System.out.println("string-Method taken: " + stringArg);
    }

    public void test(Object objectArg) {
        System.out.println("object-Method taken: " + objectArg.toString());
    }

    public <T extends Serializable> T getTestData() {
        return (T) new Integer(10);
    }

    public static void main(String[] arguments) {
        Java8Problem instance = new Java8Problem();
        instance.test(instance.getTestData());
    }

}

When i compile and run this class in Java 7 the output will be:

object-Method taken: 10

But when i compile and run this class in Java 8 i get a runtime exception:

Exception in thread "main" java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.String at Java8Problem.main(Java8Problem.java:21)

So Java 8 seems to takes the most specific method whereas Java 7 takes the most common one.

Does anybody knows if this is a bug in Java 8 or is it changed/desired behaviour? If the latter is the case is there any possibility to configure Java 8 to use the old behaviour? Or is there any other way to solve this?

BTW: i know that the problem here is caused by the return type of method getTestData but this is only a simplified example of my real world problem in which i cannot easily change the signature of that method.

Robert.E
  • 121
  • 5

1 Answers1

0

Here's a work-around to get the compiler to choose public void test(Object objectArg) in Java 8, thus avoiding the ClassCastException:

Java8Problem instance = new Java8Problem ();
instance.test(instance.<Integer>getTestData());
Eran
  • 387,369
  • 54
  • 702
  • 768