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.

3
  • @mszymborski Sure but I can't modify existing classes (like java.lang.reflect.Field) to implement it. Commented Jul 24, 2016 at 21:41
  • 4
    Do you mean <T extends Member & AnnotatedElement> void method(T o)? Commented Jul 24, 2016 at 21:43
  • 1
    @SotiriosDelimanolis Whoa. I had no idea you could do that. That's exactly the answer, you should post it. Thanks! (Sorry, resueman beat you to it!) Commented Jul 24, 2016 at 21:44

1 Answer 1

3

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

<T extends Member & AnnotatedElement> void method (T o){ /* ... */ } 
Sign up to request clarification or add additional context in comments.

1 Comment

Whoa, cool. Thanks!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.