Xtra Coder Xtra Coder - 2 months ago 5
Java Question

Class<Result> cannot be converted to Class<Result<Integer>>

Suppose I have and API method declared as following

public class Dummy {
public static class Result<ValueT extends Comparable> {
public ValueT value;
}

public static <ValueT extends Comparable> Result<ValueT>
getResult(Class<? extends Result<ValueT>> ofType) throws Exception {
return ofType.newInstance();
}
}


Now I'd like to invoke it relying on Java compile-time type verification and just can't find correct syntax to do this:

Attempts:

getResult(Result<Integer>.class)
<-- expected syntax


public static void invokeGetResult() {
Result<Integer> intResult = getResult(Result<Integer>.class);
}


results in

error: <identifier> expected
Result<Integer> intResult = getResult(Result<Integer>.class);
^


getResult(Result.class)
<-- just to try


public static void invokeGetResult() {
Result<Integer> intResult = getResult(Result.class);
}


results in

error: method getResult in class Dummy cannot be applied to given types;
Result<Integer> intResult = getResult(Result.class);
^
required: Class<? extends Result<ValueT>>
found: Class<Result>
reason: cannot infer type-variable(s) ValueT
(argument mismatch; Class<Result> cannot be converted to Class<? extends Result<ValueT>>)
where ValueT is a type-variable:
ValueT extends Comparable declared in method <ValueT>getResult(Class<? extends Result<ValueT>>)


getResult((Class<Result<Integer>>)Result.class)
<-- just to try


public static void invokeGetResult() {
Result<Integer> intResult = getResult((Class<Result<Integer>>)Result.class);
}


results in

error: incompatible types: Class<Result> cannot be converted to Class<Result<Integer>>
Result<Integer> intResult = getResult((Class<Result<Integer>>)Result.class);
^

Answer

EDIT: I did not understand clearly the original intentions. This example should work for your call, however it is a bit hacky and not so recommended.

public class Dummy {
    public static class Result<ValueT extends Comparable> {
        public ValueT value;
    }

    public static <ValueT extends Comparable> Result<ValueT>
        getResult(Class<? extends Result<ValueT>> ofType) {
        return null;
    }
}

You can call it like this:

Dummy.Result<Integer> result = Dummy.getResult(new Result<Integer>(){}.getClass());

The compile time verification should work with this example, as you are creating an anonymous empty class and it's type information can be retrieved successfully.

You could also do a type cast as @Jorn suggested in comments, although your compiler will warn you about the fact it is an "unchecked cast".

Comments