Method argument extends class implements interface
I have the following class and interface:
public class BasicObject{...}
public interface CodeObject{...}
I want to create a method in which the argument needs to be of type BasicObject and implements CodeObject. I tried the following code but it doesn't guarantee clazz to be a class that implements CodeObject.
myMethod(Class<? extends BasicObject> clazz){...}
I want to do something like this but it doesn't compile:
myMethod(Class<? extends BasicObject implements CodeObject> clazz){...}
Your pattern class has to extend BasicObject
and extend/implement CodeObject
(which is actually an interface). You can do it with multiple classes declared in the wildcard definition of the method signature, like this:
public <T extends BasicObject & CodeObject> void myMethod(Class<T> clazz)
Note that it won't work if you do it any of these ways:
-
public <T extends BasicObject, CodeObject> void myMethod(Class<T> clazz)
This is technically valid syntax, but
CodeObject
is unused; the method will accept any classes that extendsBasicObject
, no matter whether they extend/implementCodeObject
. -
public void myMethod(Class<? extends BasicObject & CodeObject> clazz)
public void myMethod(Class<? extends BasicObject, CodeObject> clazz)
These are just wrong syntax according to Java.
Here is an approach which is a bit verbose, but avoids generics headaches. Create another class which does the extending/implementing:
public abstract class BasicCodeObject
extends BasicObject
implements CodeObject {...}
Then your method can be:
public <T extends BasicCodeObject> void myMethod(Class<T> clazz) {...}