Java Generics: function parameter for a set of generic typed objects -


i working javax.validation / hibernate validation. validate annotated (e.g. @notnull @ attribute) bean, hibernate validator used javax.validation interfaces:

validator validator = validation.builddefaultvalidatorfactory().getvalidator();  public interface validator {     <t> set<constraintviolation<t>> validate(t object, class<?>... groups); }  public interface constraintviolation<t> {     string getmessage();     path getpropertypath();      t getrootbean(); } 

the goal write single method, accepts differently typed sets, like:

set<constraintviolation<tasklist>> violationstasklist = validator.validate(tasklist); set<constraintviolation<taskitem>> violationstaskitem = validator.validate(taskitem);  public void consumeviolations(set<constraintviolation<?> violations) {     // meaningful...     violations.getmessage(); } 

using wildcard ? best think came until rejected compiler message:

consumeviolations(....<?>) cannot applied consumeviolations(....<tasklist>) 

i not want write method every type t call getmessage() , pass next method.

is possible write such method? want access methods of constraintviolation interface, not dependent on type t string getmessage().

i think need is

public void consumeviolations(     set<? extends constraintviolation<?>> violations) { } 

or like

public <t, v extends constraintviolation<t>> void consumeviolations(     set<v> violations) { } 

depending on need set inside method.

this regular behavior of generics not covariant. may know a list<dog> not list<animal> , same thing applies here.


Comments

Popular posts from this blog

android - Get AccessToken using signpost OAuth without opening a browser (Two legged Oauth) -

org.mockito.exceptions.misusing.InvalidUseOfMatchersException: mockito -

google shop client API returns 400 bad request error while adding an item -