0

Given:

public void methodOne() {
    List<RuntimeException> list = new ArrayList<RuntimeException>();
    methodTwo(list);
}

public void methodTwo(List<? extends Exception> list) {

}

Is there any way to check the actual type of the list in methodTwo at run-time? I know there is similar question Get generic type of java.util.List however my question is specifically about wildcards.

Please note that the collection might be empty so checking the elements might not work.

sergeyan
  • 1,173
  • 1
  • 14
  • 28
  • If you meant getting the type of the `List`, I don't think that's possible at run-time. – Naman Mar 25 '20 at 15:28
  • 1
    Yes, a range is allowed but the actual type is specific - in this case it's RuntimeException. – sergeyan Mar 25 '20 at 15:32
  • 3
    Generics are erased at runtime. As far as the runtime is concerned, `new ArrayList();` looks the same as `new ArrayList();` You physically cannot determine this at runtime. – Sweeper Mar 25 '20 at 15:40
  • 3
    ...but if you tell us why you think you need this, we might be able to help you solve your problem in a different way. – Kayaman Mar 25 '20 at 15:43

1 Answers1

0

It is not possible to get the type at runtime due to type erasure.

The type is not stored and instead converted to either object for unbound parameters or the first bound class for bound parameters. Reference: Type Erasure

Janar
  • 2,623
  • 1
  • 22
  • 32