Reputation: 655
Example is pretty simple. What I want is written. The problems are in the comments.
import java.util.*;
class Main
{
private static class X<T> {
public static T get() { return new T(); }
}
public static void main(String[] args)
{
System.out.println(X<Interger>.get()); // illegal start of type
// commenting out above yields:
// error: non-static type variable T cannot be referenced from a static context
}
}
The real confounder to me is the error: non-static type variable T cannot be referenced from a static context
. The error seems clear: the class & method are static but the type variable isn't. Can I make the type variable work in this static context.
Further, as the example is written, I don't understand why I get an illegal start of type
error with nothing else. Is this because the error about the non-static type variable is hidden?
Upvotes: 0
Views: 1384
Reputation: 147164
You can't do new T()
. For one thing, there is no guarantee that T
has an accessible no-args constructor. Relevant here, there is no no-arg constructor for Integer
.
Static methods, as well as instance methods and constructors, can have type parameters.
public static <T> T get() {
// Can only legally return null or throw.
...
}
...
System.out.println(X.<Integer>get());
What to use instead? Possibly an abstract factory of some sort, possibly java.util.function.Supplier
.
Upvotes: 4
Reputation: 177
I think Supplier maybe more suitable for you than static X<T>.get
:
public static class aClass {}
public static <T> aMethodWantToUseX(Supplier<T> x) {
T t = x.get();
}
aMethodWantToUseX(aClass::new)
Upvotes: 1
Reputation: 20205
While the type X
is generic, the class X
is not. In Java, there are no "generic classes" (only generic types). What was most probably intended is a generic parameter on the static method:
private static class X<T> {
public static <T> T get() {
return ...;
}
}
Also, since generics are erased, one cannot instantiate T
(thus the three dots in the code above).
One would call the method like such:
...
X.<SomeConcreteType>get();
Upvotes: 1