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?
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:
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():This collection will now throw an exception if you try to insert something that isn’t a
String.