C#与Java:其中T:新的()语法 [英] C# to Java: where T : new() Syntax

查看:185
本文介绍了C#与Java:其中T:新的()语法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我移植一些C#代码到Java的。我有与语法的地方,特别是新的()的麻烦。我明白,哪里是类似于Java的泛型:T已延伸FOO。



如何,我可以在Java中复制新的()说法?



< A HREF =htt​​p://msdn.microsoft.com/en-us/library/6b0scde8%28VS.80%29.aspx相对=nofollow>新的()约束让编译器知道,任何类型参数必须提供可访问的无参数 - 或者default--构造函数。 - MSDN



如:

 公共类BAR< ; T> :BAR 
,其中T:FOO,新的()

下面是我如何实现克莱的解决方案

 公共类BAR<吨延伸FOO>扩展ABSTRACTBAR {
公共BAR(T T)抛出InstantiationException,IllegalAccessException {
t.getClass()的newInstance()。
THIS.VALUE = T;
}
}


解决方案

您不能复制在Java中,因为泛型是C#和Java之间的根本不同。 Java使用类型擦除所以泛型类型参数不(大部分)保留在运行时。如果你想构建你的泛型类型参数的元素,那么你就需要在一个类的实例来传递:

 公共类巴≤ ;吨延伸美孚> {
私人final类< T> clazz所;

公共类酒吧(类< T> clazz所){
this.clazz = clazz所;
}

公开的newInstance牛逼(){
返回clazz.newInstance(); //这将抛出checked异常
}
}

修改只是为了掩饰的泛型类型参数的运行时类型安全问题:明确的Java没有的本地的拥有它,因为类型擦除:有没有运行时类型泛型类型参数。然而有一个解决方案。您可以使用 Col​​lections.checkedList()



 列表<串GT;清单= Collections.checkedList(新的ArrayList<串GT;(),
为String.class);

这集现在会抛出一个异常,如果您尝试插入的东西是不是一个字符串


I am porting some C# code over to Java. I am having trouble with the where Syntax, specifically new(). I understand that where is similar to Java's generic: T extends FOO.

How I can replicate the new() argument in Java?

"The new() Constraint lets the compiler know that any type argument supplied must have an accessible parameterless--or default-- constructor." - MSDN

ie:

public class BAR<T> : BAR
       where T : FOO, new()

Here is how I implemented cletus's solution:

public class BAR<T extends FOO> extends ABSTRACTBAR {
    public BAR(T t) throws InstantiationException, IllegalAccessException{ 
        t.getClass().newInstance();
        this.value = t;
    }
}

解决方案

You can't replicate that in Java because generics are fundamentally different between C# and Java. Java uses type erasure so generic type arguments aren't (mostly) retained at runtime. If you want to construct elements of your generic type argument then you'll need to pass in a class instance:

public class Bar<T extends Foo> {
  private final Class<T> clazz;

  public class Bar(Class<T> clazz) {
    this.clazz = clazz;
  }

  public T newInstance() {
    return clazz.newInstance(); // this will throw checked exceptions
  }
}

Edit: Just to cover the issue of runtime type safety of generic type arguments: clearly Java doesn't natively have it because of type erasure: there are no runtime types for generic type arguments. There is a solution however. You use Collections.checkedList():

List<String> list = Collections.checkedList(new ArrayList<String>(),
                      String.class);

This collection will now throw an exception if you try to insert something that isn't a String.

这篇关于C#与Java:其中T:新的()语法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆