我在一个C#项目中有一个方法,它看起来像这样:
public T AddEC<T>() where T : EntityComponent, new() {
if (!HasEC<T>())
{
T nComponent = new T();
}
}
我最近才开始正式使用Java泛型,但我不知道如何移植像这样的方法,或者是否由于语言限制而无法移植,有人能帮忙吗?
我在一个C#项目中有一个方法,它看起来像这样:
public T AddEC<T>() where T : EntityComponent, new() {
if (!HasEC<T>())
{
T nComponent = new T();
}
}
我最近才开始正式使用Java泛型,但我不知道如何移植像这样的方法,或者是否由于语言限制而无法移植,有人能帮忙吗?
这是一篇非常好的文章。
http://www.jprl.com/Blog/archive/development/2007/Aug-31.html
来自该来源。
Java type and method constraints are specified using a "mini expression language" within the '<' and '>' declaring the generic type parameters. For each type parameter that has constraints, the syntax is:
TypeParameter ListOfConstraints
Where
ListOfConstraints
is a '&'-separated list of one of the following constraints:
- Specifying a base class or implemented interface on the Generic Type Argument by using: extends BaseOrInterfaceType
('&' must be used instead of ',' because ',' separates each generic type parameter.)
这里有一个例子
class GenericClass<T extends Number & Comparable<T>> {
void print (T t) {
System.out.println (t.intValue ()); // OK
}
}
public <T extends EntityComponent> T addEC(Class<T> entity) {
但那并不能真正做到我想要的。我需要它像我的C#示例一样工作。 :( - DominicEU