I am writing a method which requires that one of its arguments descend from a particular class ( MyClass
) and implement an interface ( MyInterface
).
A crude way of doing this would be
public void doStuff(MyClass arg0) {
if (!(arg0 instanceof MyInterface))
throw new IllegalArgumentException("arg0 must implement MyInterface");
// do whatever we need to do
}
Note that MyClass
does not implement MyInterface
, 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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.