I have the following example:
public class main3
{
static class Value<T>
{
T value;
Value (T value) { this.value = value; }
}
static class IntegerValue extends Value<Integer>
{
IntegerValue (Integer value) { super (value); }
IntegerValue (String value) { super (Integer.valueOf (value)); }
}
static <T> IntegerValue integer (T value) { return new IntegerValue(value); }
public static void main (String ...argv)
{
IntegerValue a = new IntegerValue (42);
IntegerValue b = new IntegerValue ("42");
IntegerValue c = integer (42);
IntegerValue d = integer ("42");
}
}
This fails with the error:
main3.java:15: error: no suitable constructor found for IntegerValue(T)
static <T> IntegerValue integer (T value) { return new IntegerValue(value); }
^
constructor IntegerValue.IntegerValue(Integer) is not applicable
(argument mismatch; T cannot be converted to Integer)
constructor IntegerValue.IntegerValue(String) is not applicable
(argument mismatch; T cannot be converted to String)
where T is a type-variable:
T extends Object declared in method <T>integer(T)
1 error
How to specify the right type of T
when calling the generic integer
method?
I tried also this:
IntegerValue c = main3.<Integer>integer (42);
IntegerValue d = main3.<String>integer ("42");
But it does not help.