Java Generic type inference derived from return method type

public class TestCase {
    public static String compiles() {
        return getAction();
    }

    /*
    public static String doesntCompile1() {
        return (String) getAction();
    }

    public static String doesntCompile2() {
        return TestCase.<String> getAction();
    }
    */

    public static <T extends javax.swing.Action> T getAction() {
        return (T) null;
    }
}

If this is considered an error in javac v1.6.0_22 and jdt v3.7.1? For me, it looks like this, because in other cases, the compiler really finds a potential ClassCastException. In the compilation method, this will be executed with a ClassCastException at runtime.

The source code that resulted in this example did not compile in javac, printing the following exception. Unfortunately, the sample code that I provided for some reason will not generate this error.

type parameters of <T>T cannot be determined;
no unique maximal instance exists for type variable T with upper bounds
+5
source share
2 answers

I would expect a good compiler to be able to detect an error, but as an optimization. You represent a specific case of a more general case:

public class TestCase {
    public static TypeA methodA() {
        return methodB();
    }

    public static <T extends TypeB> T methodB() {
        return (T) null;
    }
}

, , , :

  • TypeA TypeB , TypeB TypeA.
  • TypeA TypeA TypeB.

, , - №2, . , String - . , # 2 , .

, String CharSequence. , . , .

javac, , . , .

. : java.lang.String. : T.

, , , - :

public static CharSequence compiles() {
    return (CharSequence)getAction();
}

.

+2

, / . , , .

doesntCompile1

Action to String

- , a T, Action, , Action String.

doesntCompile2

: getAction() TestCase (). String

,

?

0

All Articles