2

I'm using List.class because List<String>.class is wrong. Is there a syntax that gets the class of the parametrized class?

Code:

import java.util.List;
import org.apache.camel.Message;
...
    Message m = exchange.getIn();
    List<String> serviceIds = null;
    serviceIds = m.getHeader("serviceId", List.class);

Of course I would rather have:

    serviceIds = m.getHeader("serviceId", List<String>.class);

to ensure that getHeader would return null if a list of something not strings was in the header.

Julian
  • 1,522
  • 11
  • 26

2 Answers2

7

You cannot give it a class of List<String>, because there is no such class: the type of <String> is removed by the compiler during the process known as type erasure, leaving you with pure List.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
  • Looks like I've got the best I can do. Not too impressed with Java here. Thanks for the input. – Julian Sep 21 '12 at 16:02
3

I'm not entirely sure I understand your question, but if you have a List parameterized with some class, eg:

List<Cat> myCats = new ArrayList<Cat>();

And you have some API method that you want to call:

public static void doSomething(Class<T> clazz);

And you're looking to provide that method with Cat.class, there is unfortunately no way to determine (at runtime) the parameterized class that is being contained in the List. This information is erased at runtime.

I believe your question may be a duplicate of this one, but don't hesitate to correct me if I'm mistaken:

How to get the generic type at runtime?

Community
  • 1
  • 1
Craig Otis
  • 31,257
  • 32
  • 136
  • 234