dimanche 8 janvier 2017

Get collection type through reflection [duplicate]

This question already has an answer here:

I wonder if it's possible to get a collection's item type from a local variable or parameter? Let's say I have the following code:

public static <T> void addCollection(Collection<T> col){
    // infer that T is Foo from the given collection
    // result is ideally a String of the form: "Foo.class"
}

public static void main(String[] args){
    Collection<Foo> foo = new HashSet<Foo>();
    foo.add(new Foo());
    foo.add(new Foo());
    addCollection(foo);
}

Some existing examples that accomplish this, make use of reflection to first grab the fields of a class and cast it to a ParameterizedType. An example here: Java get generic type of collection Is the same possible when the collection is a parameter?





Aucun commentaire:

Enregistrer un commentaire