I'd like to to something like the following in Java and don't really know what to searc开发者_Go百科h 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.
You can only use this function with all types in the generic definition
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?
精彩评论