java - Why does this method call fail? (Generics & wildcards) -


i getting below error:

'call(containsmonitor)' cannot invoke 'call(? extends webscout.monitor)' in 'webscoutcallable' 

monitor.java

webscoutcallable<? extends monitor> handler;  public setcallable(webscoutcallable<? extends monitor> callable) {      this.handler = callable; } 

webscoutcallable.java

public interface webscoutcallable<t extends monitor> {      public void call(t caller); } 

containsmonitor.java

public class containsmonitor extends monitor {      public void handledocument() {           handler.call(this);      } } 

i'll freely admit i'm new generics , still quite new java itself. find error message confusing looks should work (method declaration expects monitor or subclass, i'm passing in subclass). (+explanation) appreciated!

thanks!

you have wildcard in type parameter of handler variable. compiler doesn't know exact type of type parameter is, it's either monitor or subclass.

the call method takes t, matched on wildcard. there no guarantee wildcard type containsmonitor. monitor, or monitorsubtypethatdoesntexistyet. because compiler doesn't know actual type, cannot allow pass except null, because non-null argument, can't guarantee type safety.

you can around removing wildcard, , replacing concept type parameter on monitor class.

class monitor<t extends monitor<t>> {     webscoutcallable<t> handler;      public void setcallable(webscoutcallable<t> callable) {          this.handler = callable;     } } 

the interface webscoutcallable changes little in response:

interface webscoutcallable<t extends monitor<t>> {     public void call(t caller); } 

the subclass feeds own name type argument when extending monitor.

class containsmonitor extends monitor<containsmonitor> {      public void handledocument() {           handler.call(this);      } } 

now, t known type, , containsmonitor defines itself, it's legal pass call.


Comments

Popular posts from this blog

PHP DOM loadHTML() method unusual warning -

python - How to create jsonb index using GIN on SQLAlchemy? -

c# - TransactionScope not rolling back although no complete() is called -