0

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.

Jason C
  • 38,729
  • 14
  • 126
  • 182

1 Answers1

3

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

<T extends Member & AnnotatedElement> void method (T o){ /* ... */ }
resueman
  • 10,572
  • 10
  • 31
  • 45