1

I have a class containing a static create method.

public class TestClass {

 public static <E> TestClass<E> create() {
    return new TestClass<E>();
  }

}

when I use TestClass.create() , it can be compiled. But when I use TestClass<String>.create(), it failed to compile, how to specify the generic?

nemesv
  • 138,284
  • 16
  • 416
  • 359
Adam Lee
  • 24,710
  • 51
  • 156
  • 236
  • This [link][1] might help you... [1]: http://stackoverflow.com/questions/936377/static-method-in-a-generic-class – Fahim Parkar Jan 14 '12 at 07:48
  • Your example isn't a generic class, it is a generic method. – Mark Rotteveel Jan 14 '12 at 08:40
  • Shouldn't the class declaration be `public class TestClass` or `public class Something`? I'm irritated that the class body uses TestClass as a generic when the declaration is concrete!? – ThomasH Sep 14 '16 at 08:26

3 Answers3

10

Assuming you are asking about specifying the type explicitly in case type inference fails, you can use TestClass.<String>create() (notice how the type is after the . as opposed to before).

Sanjay T. Sharma
  • 22,857
  • 4
  • 59
  • 71
  • Thanks. why the syntax like this, very counter-intuitive? – Adam Lee Jan 14 '12 at 07:44
  • I don't think anyone expect those who designed generics would be able to answer that but I think it's to differentiate between creation of a generic class and supplying additional type parameters to generic method of a non-generic class. – Sanjay T. Sharma Jan 14 '12 at 07:51
  • 5
    Th syntax is not counter-intuitive to me. The generic parameter is part of the method signature and not the class signature. Therefor is should come after the dot. Note that in most cases the Generic type ca be inferred and this explicit type information is redundant, just like `List strings = Collections.emptyList();` – M Platvoet Jan 14 '12 at 07:57
  • 2
    @M Platvoet: It's counter-intuitive because the type parameter comes after the dot and not the method name. – Sanjay T. Sharma Jan 14 '12 at 08:05
4

Yeah, that's pretty... unintuitive.

A sidenote from Josh Bloch's presentation of his Effective Java, 2nd Edition about the issue: "God kills a kitten every time you specify an explicit type parameter". I would like to avoid constructs like this but sometimes it cannot be evaded.

The trick is to specify the generic parameter after the . character: TestClass.<String>create().

rlegendi
  • 10,466
  • 3
  • 38
  • 50
1

The generic type can be specified in the class declaration:

public class TestClass<E> {

    public static <E> TestClass<E> create() {
        return new TestClass<E>();
    }
}

// Elsewhere in the code
TestClass<String> testClass = TestClass.create();
matsev
  • 32,104
  • 16
  • 121
  • 156