2015-09-11 115 views
6

我在Java中看到,可以使类泛型和泛型方法。我也看到了使构造函数与Class一起通用的代码。我只能使通用构造函数?如果是的话,如何调用构造函数?我可以制作一个通用的构造函数吗?

+1

http://stackoverflow.com/questions/32304427/why-is-it-wrong-to-supply-type-parameter-in-the-constructor-of-a-generic-class/32304725# 32304725 – ZhongYu

+1

尽管有可能我更感兴趣为什么要为非泛型类创建泛型构造函数。或者更一般地说,为什么这样的构造函数是可能的。 – Pshemo

+0

@Pshemo - 构造函数就像一个方法,所以为什么它不能通用?:) – ZhongYu

回答

4

是的,你可以。

class Example { 

    public <T> Example(T t) {} 

    public static void main(String[] args){ 

     // In this example the type can be inferred, so new Example("foo") 
     // works, but here is the syntax just to show you the general case. 
     Example example = new<String>Example("foo"); 
    } 
} 
+0

谢谢@保罗Boddington ....有点这样想,但不知道的语法 – Birendra

+0

@Birendra我也不确定。我知道这是可能的,但经过一些实验后,我管理了它!我从来没有见过这样做的理由。 –

+0

你也可以写'新的例子(“foo”)' – wero

相关问题