1 Reply Latest reply: Jul 21, 2011 10:49 AM by 802316 RSS

    Parametrized collection get parametrized type

    877121
      Collection<String> x = new ArrayList<String>();

      Please anybody knows How can I obtain by reflection String Class from x ?

      Class<?> xClass = (Class<?>) ((ParameterizedType)x.getClass().getGenericSuperclass()).getActualTypeArguments()[0];

      This return "E" :((
        • 1. Re: Parametrized collection get parametrized type
          802316
          Due to type erasure, you cannot obtain a generics this way.
          You can obtain the generic type of a parent if a specific class was used.
          Collection<String> x = new ArrayList<String>() {}; // creates a subclass of ArrayList
          However, this approach is not recommended. If you must know the type, you can create a checked collection which stores the type.