简体   繁体   中英

generic type to static method

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?

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 .

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();

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM