(How) Can I do this using Java Generics?

I would like something like Java in Java and don't know what to look 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 } 

Basically, I would like the Validator # validate parameter type to be the same as the generic Subject type.

I could write it like this:

 public interface Validator<A,B extends Subject<A>> { Set<InputErrors> validate(final A thing); } 

But that would require me to declare instances that look verbose

  private Validator<String,EMailAddress> validator; 
+4
source share
3 answers

Yes, the solution you show, no matter how complicated it is, is the only way to do this job. You must list all parameters of the type type, including nested ones, in the parameter list.

+3
source

You can use this function only for all types in the general definition.

0
source

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

This may be a sign of suboptimal design: what is the Validator interface? This is difficult to understand because your example is incomplete: it does not use your type B parameter at all. Is it about checking A or about approving the Subjects? If so, then is it possible he is mixing two problems that should not be mixed?

0
source

All Articles