generic type to static method

user2183336 :

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?

Tom Hawtin - tackline :

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.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=170848&siteId=1