DominicEU DominicEU - 1 year ago 111
Java Question

Java generics vs C# where keyword

I have a method in a C# project that looks like this

public T AddEC<T>() where T : EntityComponent, new() {
if (!HasEC<T>())
T nComponent = new T();

Now I have only recently started properly working with Java Generics, but I have no idea how i'd port a method like this, or if its even possible due to the language constraints, can anyone help?

Answer Source

This is a very good article.

From that source

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