Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Java generics in interfaces

Tags:

java

generics

I'd like to create an interface that has the following methods:

public interface MyInterface {
  public Class<X> getClass();
  public void handle(X message);
}

Where X has to be the same type in both methods. The reason I need to do this is I'm getting messages that are blobs that need to be casted into the appropriate class (using getClass) and then I'd like to force implementers to implement a handle method that takes the appropriate class (instead of assuming there is one and using reflection to call it).

It seems like the only way to do this is to add a type param to the interface like so:

public interface MyInterface<T> {
...
}

but that is less than ideal because of cascading dependencies that would require specifying that type in various other classes. Any suggestions? Thanks!

like image 793
Peter Avatar asked Oct 07 '22 23:10

Peter


1 Answers

Where X has to be the same type in both methods

You can not enforce 2 methods of an interface to depend one another just by the definition.
getClass and handle will always be 2 separate methods.
What you perhaps should be doing is have 1 method, the handle and pass as a parameter a type of the class (could be something as simple as an Enum or any indicator) and delegate to a Factory to create the appropriate class to be used inside the handle method.
So handle method would (eventually) get the appropriate class to work with.

like image 101
Cratylus Avatar answered Oct 13 '22 10:10

Cratylus