Gab Gab - 1 year ago 94
Java Question

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 need to be of type BasicObject and implements CodeObject. I tried this code but it doesn't guarantee clazz to be a class that implements CodeObject.

myMethod(Class<? extends BasicObject> clazz){...}

I want to do somethign like this but this code doesn't compile :

myMethod(Class<? extends BasicObject implements CodeObject> clazz){...}

Answer Source

Your pattern class have to extends BasicObject and extends/implements CodeObject (which actually is an interface), so you can do it with multiple class declaring in wildcard definition of method signature, like that:

public <T extends BasicObject & CodeObject> void myMethod(Class<T> clazz)

Mark that it won't work if you code that:

public <T extends BasicObject, CodeObject> void myMethod(Class<T> clazz)

In that case method signature will accepts only classes that extends BasicObject, no matter if CodeObject extends/implements.

You also cannot do like that:

public void myMethod(Class<? extends BasicObject & CodeObject> clazz)


public void myMethod(Class<? extends BasicObject, CodeObject> clazz)

It's just wrong notation according Java.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download