Get generic parameter of unknown collection object

Discussion in 'Plugin Development' started by DarkBladee12, Mar 8, 2014.

Thread Status:
Not open for further replies.
  1. Offline

    DarkBladee12

    Hey guys, I've been trying to create a system which allows you to load certain variables from a config automatically. So I made a couple of converters for specific types and also one for a collection, but that's not as easy as I thought. I have to check if the generic parameter of the collection variable in the class is the same as the generic parameter of the object the config returns me, but I can't figure out how I can access that parameter. So for example Object o = new ArrayList<String>() would return the String class as generic parameter. I've already tried things like ((ParameterizedType) o.getClass().getGenericSuperclass()).getActualTypeArguments()[0] but that only returns sun.reflect.generics.reflectiveObjects.TypeVariableImpl instead of the actual type. This method only works if I define it like this List<String> o = new ArrayList<String>() which is pointless for me :/
     
  2. Offline

    caseif

    I'm assuming you got the line of code you posted from here. If that's the case, then it looks like you just need to cast it to List<T>.
     
  3. Offline

    DarkBladee12

    ShadyPotato That doesn't work, here's my current method which converts an object from the config to a collection:

    Code:java
    1. @SuppressWarnings({ "unchecked", "rawtypes" })
    2. public static <V, T extends Collection<V>> T convert(Collection<?> source, Class<?> type) throws ConversionException {
    3. try {
    4. T result;
    5. if (type.isInterface() || Modifier.isAbstract(type.getModifiers())) {
    6. if (Set.class.isAssignableFrom(type)) {
    7. if (SortedSet.class.isAssignableFrom(type))
    8. result = (T) new TreeSet();
    9. else
    10. result = (T) new HashSet();
    11. } else
    12. result = (T) new ArrayList();
    13. } else
    14. result = (T) type.newInstance();
    15. Converter<V> converter = null;
    16. for (Object value : source) {
    17. if (converter == null)
    18. converter = (Converter<V>) ConversionHandler.getConverter(value.getClass());
    19. result.add(converter.convert(value));
    20. }
    21. return result;
    22. } catch (Exception e) {
    23. throw new ConversionException(type, e);
    24. }
    25. }


    But currently I have no check if the generic parameter of the source matches with the actual type.
     
  4. Offline

    DarkBladee12

    Does anyone know how to solve this?
     
Thread Status:
Not open for further replies.

Share This Page