Jason C Jason C - 4 months ago 12
Java Question

Declaring a variable as more than one interface

Is there a way to specify a type that is more than one interface, and have the type check be done at compile time?

Example: Let's say I have a method like

void method (Object o) { ... }


But I want to constrain
o
at compile time to something that implements both
java.lang.reflect.Member
and
java.lang.reflect.AnnotatedElement
(e.g.
Class
,
Field
,
Method
, etc.), and access the methods of both interfaces ideally without casting
o
.

There are plenty of ways to do this at run-time, I'm just specifically curious about a compile-time check.

Answer

Yes, you can do that with generics. Define your method like this:

<T extends Member & AnnotatedElement> void method (T o){ /* ... */ }
Comments