Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
323 views
in Technique[技术] by (71.8m points)

java - (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);
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.9k users

...