user149408 user149408 - 3 months ago 6x
Android Question

Specify that a method argument must inherit from one class and implement an interface

I am writing a method which requires that one of its arguments descend from a particular class (

) and implement an interface (

A crude way of doing this would be

public void doStuff(MyClass arg0) {
if (!(myClass instanceof MyInterface))
throw new IllegalArgumentException("arg0 must implement MyInterface");
// do whatever we need to do

Note that
does not implement
, and both are classes that I import as they are.

Is there a more elegant way of doing this, preferably one that would already flag errors at build time?


You can do that with the following generic method:

public <T extends MyClass & MyInterface> void doStuff(T arg) { ... }

Assuming the following classes (and interfaces)

class MyClass {}
interface MyInterface {}

class A extends MyClass {}
class B implements MyInterface {}
class C extends MyClass implements MyInterface {}

the following two statements are illegal (compiler error)

doStuff(new A());
doStuff(new B());

whereas the following statement will compile

doStuff(new C());

See JLS ยง4.4 (Type Variables) for more information about the somehwat weird type variable declaration.