简体   繁体   中英

(How) Can I do this with Java Generics?

I'd like to to something like the following in Java and don't really know what to search for:

public interface Subject<T> {
}

public interface EMailAddress extends Subject<String> {
}

public interface Validator<T extends Subject<V>> {
  Set<InputErrors> validate(final V thing); // this does not compile
}

I basically would like the parameter type of Validator#validate be the same as the generic type of Subject.

I could write it like this:

public interface Validator<A,B extends Subject<A>> {

  Set<InputErrors> validate(final A thing);
}

But this would require me to declare instances like this, which seems verbose

 private Validator<String,EMailAddress> validator;

Yes, the solution you show, however verbose, is the only way to make this work. You must list all generic type parameters, including nested ones, in your parameter list.

您只能在泛型定义中将此函数与所有类型一起使用

There is no way to refer to nested type parameters. If you need both X and Subject as type parameters, you need two type parameters.

This may be a sign of a non-optimal design: What is the Validator interface really about? It's hard to see because your example is incomplete: it doesn't use your B type parameter at all. Is it about validating A or about validating Subjects? If it does both, then maybe it's mixing two concerns that it shouldn't be mixing?

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