How to call static method from a generic class?

前端 未结 3 856
既然无缘
既然无缘 2021-01-16 13:46

I have a class containing a static create method.

public class TestClass {

 public static  TestClass create() {
    return new TestClass&l         


        
相关标签:
3条回答
  • 2021-01-16 14:19

    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).

    0 讨论(0)
  • 2021-01-16 14:22

    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();
    
    0 讨论(0)
  • 2021-01-16 14:24

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

    0 讨论(0)
提交回复
热议问题