Java Reflection: What does my collection contain?

I defined a method in the class:

public void setCollection(Collection<MyClass>);

and in another class

public void setCollection(Collection<OtherClass>);

(and indeed, many similar classes)

Everyone is in classes with the same superclass, and I have a method in the support class where I want to call this method and set it with elements of the correct class type. Now I can get me to set the collection by doing

Method setter = ...;
Class<?> paramClass = setter.getParameterTypes()[0]; // Is Collection in this case
if(paramClass.equals(Collection.class)) {
  HashSet col = new HashSet();
  // fill the set with something
  setter.invoke(this, col);
}

But how can I determine which class the objects in this collection should belong to?

Greetings

Nick

+5
source share
5 answers
Method.getGenericParameterTypes();

returns an array of types that takes a parameter. Complexity increases exponentially from there.

In your specific case, this will work:

    Method m = Something.class.getMethod("setCollection", Collection.class);
    Class<?> parameter = (Class<?>) ((ParameterizedType) m.getGenericParameterTypes()[0]).getActualTypeArguments()[0];

, , . , , . , , , getGenericParameterTypes(), getActualTypeArguments(). .

+9

setCollection , - ( , , ).

, . , , , . "init" ( , , ).

public class Main 
{
    public static void main(String[] args) 
    {
        List<Car> car;
        List<Bar> bar;

        car = new ArrayList<Car>();
        bar = new ArrayList<Bar>();
        init(car, new CarCreator());
        init(bar, new BarCreator());
    }

    private static <T> void init(final List<T>    list,
                                 final Creator<T> creator)
    { 
        for(int i = 0; i < 10; i++)
        {
            final T instance;

            instance = creator.newInstance(i);
            list.add(instance);
        }
    }
}

interface Foo
{    
}

class Bar implements Foo 
{ 
}

class Car implements Foo 
{ 
}

interface Creator<T>
{
    T newInstance(int i);
}

class BarCreator
    implements Creator<Bar>
{
    public Bar newInstance(final int i)
    {
        return (new Bar());
    }
}

class CarCreator
    implements Creator<Car>
{
    public Car newInstance(final int i)
    {
        return (new Car());
    }
}
+2

Java . , - . , , .

.

, :

public <T> String doSomething(T first, int second) {
    return first.toString();
}

( T):

<T:Ljava/lang/Object;>(TT;I)Ljava/lang/String

, , , .

+1

, , . , MyClass OtherClass ( , ) . .

0

candiru, " " , .

public void setCollection(Collection<T> aCollection, Class<T> elementType);

, " ", :

public void setCollection(Collection<MyClass> myClassCollection, 
                          Class<MyClass> clazz);

:

Collection<MyClass> myClassCollection = new ArrayList<MyClassCollection>();
setCollection(myClassCollection, MyClass.class);

, , , , , ;)

0
source

All Articles