securenai securenai -4 years ago 78
Java Question

(Generics)Cannot make a static reference to the non-static type T

running the Demo class will invoke a static method newInstance in SomeClass to call the constructor and printing hello

defining a method will include a return type + method name with arguments

the return type for newInstance is <T>SomeClass<T> seems weird to me
since my class is called SomeClass<T> instead of <T>SomeClass<T>


why do i need the <T> in front of the SomeClass<T> ?
it seems that if I don't include it there will be an common error
called Cannot make a static reference to the non-static type T


another thing to point out is that I can put many spaces between <T> and SomeClass<T> so it doesn't seem like they need to be together.

public class SomeClass<T> {

public static <T>SomeClass<T> newInstance(Class<T> clazz){
return new SomeClass<T>(clazz);
}

private SomeClass(Class<T> clazz){
System.out.println("hello");
}
}

public class Demo {

public static void main(String args[])
{
SomeClass<String> instance = SomeClass.newInstance(String.class);
}
}

Answer Source

What is a static method? A Method that works on the class, and not a specific instance. The generic parameter T in the class signature public class SomeClass<T> is only available for a specific instance (hence non-static type T). e.g. SomeClass<String> where the [T = String].

By including <T> in the method signature of public static <T>SomeClass<T> newInstance(Class<T> clazz). You're saying that; for this method, there is a generic type argument T. This T is separate from the T in the class signature. So it might as well be C i.e. public static <C> SomeClass<C> newInstance(Class<C> clazz). Or something completely different.

But if you don't include <T> with the method, the compiler thinks you're trying to use the T in the class signature. Which is illegal.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download