Java generics vs c # where the keyword

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

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

Now I just recently started working correctly with Java Generics, but I have no idea how I could port such a method, or even if it is possible due to language restrictions, can anyone help?

+4
source share
2 answers

This is a very good article.

http://www.jprl.com/Blog/archive/development/2007/Aug-31.html

From this source

Constraints of the Java type and method are set using the "mini expression language" within the limits of '<' and '>', declaring the general type of parameters. For each type parameter that has restrictions, the syntax is:

 TypeParameter ListOfConstraints 

Where ListOfConstraints is '&' is a selected list of one of the following restrictions:

  • Specifying a base class or implemented interface on Generic Type Argument using: extends BaseOrInterfaceType

('&' should be used instead of ',' because ',' shares each common type.)

+2
source

Here is an example

 class GenericClass<T extends Number & Comparable<T>> { void print (T t) { System.out.println (t.intValue ()); // OK } } 

In this example, Number and Comparable are constraints since they appear in the where clause of a C # class declaration.

+2
source

Source: https://habr.com/ru/post/1414365/


All Articles