Setting the type of the collector type at run time (Java Reflection)

I would like to get a generic collection type using reflection at runtime.

Code (JAVA):

Field collectionObject = object.getClass().getDeclaredField(
    collectionField.getName());
//here I compare to see if a collection
if (Collection.class.isAssignableFrom(collectionObject.getType())) {
   // here I have to use the generic type of the collection 
   // to see if it from a specific type - in this case Persistable
   if (Persistable.class.isAssignableFrom(GENERIC_TYPE_COLLECTION.class)) {
   }
}

Is there a way to get a generic collection type in java at runtime? In my case, I need a class. The class is of a general type.

Thanks in advance!

+5
source share
4 answers

The erasure type means that information about the general type of the object is simply not available at run time.

(Link to the corresponding section of Angelika Langer Java Generics Frequently Asked Questions , which should answer almost every question you could ask about Java generics:)

- . , , , :)

, . :

import java.lang.reflect.*;
import java.util.*;

public class Test
{
    public List<String> names;

    public static void main(String [] args)
        throws Exception // Just for simplicity!
    {
        Field field = Test.class.getDeclaredField("names");

        ParameterizedType type = (ParameterizedType) field.getGenericType();

        // List
        System.out.println(type.getRawType());

        // Just String in this case
        for (Type typeArgument : type.getActualTypeArguments())
        {
            System.out.println("  " + typeArgument);
        }
    }
}

T List<T>, , .

- . , - :

public class StringCollection implements Collection<String>

StringCollection, . getGenericSuperType getGenericInterfaces , , .

, . , , .

+17

, . , , , , .

class Thing {
  List<Persistable> foo;
}


Field f = Thing.class.getDeclaredField("foo");
if( Collection.class.isAssignableFrom( f.getType() ) {
   Type t = f.getGenericType();
   if( t instanceof ParameterizedType ) {
     Class genericType = (Class)((ParameterizedType)t).getActualTypeArguments()[0];
     if( Persistable.class.isAssignableFrom( genericType ) )
         return true;
   }
}

, ,

Class Thing<T> {
  List<T> foo;
}

.

+9

, , Field.getGenericType. , , (, , ), , ..

0
source

Copied from my post: fooobar.com/questions/111150 / ...

I used a similar solution for what it explains here for several projects, and found it quite useful.

http://blog.xebia.com/2009/02/07/acessing-generic-types-at-runtime-in-java/

Its essence is to determine the type parameter at runtime:

public Class returnedClass {
  ParameterizedType parameterizedType =
    (ParameterizedType) getClass().getGenericSuperClass();
 return (Class) parameterizedtype.getActualTypeArguments()[0];
}
0
source

All Articles