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){...}
Best Solution
Your pattern class has to extend
BasicObject
and extend/implementCodeObject
(which is actually an interface). You can do it with multiple classes declared in the wildcard definition of the method signature, like this: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.