简体   繁体   中英

Restrict Java Generic to a Class

In C#, this is possible:

public interface IMyCoolInterface<TEntity> where TEntity : class
{
}

So the generic is confined / restricted to a class.

Is this possible with Java?

Generic parameters are always classes in Java. There's no other option. The language doesn't allow primitives to be parameters, and there's no equivalent to C#'s struct .

You can restrict it even further if you want the interface to be of a certain base type by adding the extends keyword within your generic

public interface MyGenericInterface<T extends List<?>> {

  T convert(String value);

}

Now every class that implements MyGenericInterface must use an object that extends List in its implementation

public class MyClass implements MyGenericInterface<ArrayList<String>> {

  @Override
  public ArrayList<String> convert(String value) {
    return new ArrayList<>();
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM