tags:

views:

100

answers:

3

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 so:

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;
+3  A: 

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.

Péter Török
A: 

You can only use this function with all types in the generic definition

kafbuddy
A: 

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?

Wouter Coekaerts
I'll try to clarify: I want to be able to optain i.e. a Validator<EMailAddress> through a Service-Locator.
msung
[...] I tried to differentiate between what I want to validate (e-mail-addresses, usernames, phonenumbers) and how it is represented in this context (here as a String, could be an Integer when validating IDs).
msung