Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

generics

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);
    }
}
like image 712
securenova Avatar asked Apr 03 '16 13:04

securenova


People also ask

Can generic methods be non-static?

Static and non-static generic methods are allowed, as well as generic class constructors. The syntax for a generic method includes a list of type parameters, inside angle brackets, which appears before the method's return type.

How do you reference a non-static method from a static method?

You cannot refer non-static members from a static method. Non-Static members (like your fxn(int y)) can be called only from an instance of your class. or you can declare you method as static. Save this answer.


1 Answers

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.

like image 187
Jorn Vernee Avatar answered Oct 05 '22 14:10

Jorn Vernee