Java : How to get type of List<?>

Viewed 17050

I'm working on reflection in java. I know this is a common question and there are a lot of articles about it but I'm a bit confused and can't seem to find the right solution for what I'm trying to achieve.

I have :

public class ClassA {
    private List<?> myList;
    // getters, setters
}

"myList" will contain a list of objects (DTOs) :

List<?> myList; // could be List<DTO1> or List<DTO2> ...

I'm trying to get the type of the list from another class like this :

public class ClassB {
    public void myMethod() {
        // get type of ClassA.getMyList()
    }
}

I can only get "ArrayList" when I try using stuff like getClass(), getType()... Trying to get the class of an element in the list results in "LinkedHashMap".

I really want to achieve this by using a wildcard type for the list.

So is there a way I can get the type of myList with minimal code ?


EDIT :

Thank you all for your answers.

Just one thing : myList contains elements of type LinkedHashMap, this wasn't very clear on my post.

It seems this really can't be done. Each LinkedHashMap represents an object but you can't know which one. They are just a list of keys + values.

2 Answers

You can try this. I dont know it will solve your purpose or not but may be help.

 import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

public class App {
    public static void main(String[] args) {
       ClassA classA = new ClassA();

       List<String> strs = new ArrayList<>();

       strs.add("A");
       strs.add("B");

       classA.setRepos(strs);

        String typeOfList = classA.getRepos().getClass().getTypeName();
        System.out.println("Type of variable in classA : "+typeOfList);

        String typeOfListData = classA.getRepos().get(0).getClass().getTypeName();
        System.out.println("Type of data inside the list : "+typeOfListData);

       for (String s: (List<String>)classA.getRepos())
       {
           System.out.println(s);
       }
    }

}

ClassA will be like this

import java.util.List;

public class ClassA {
    private List<?> repos;

    public List<?> getRepos() {
        return repos;
    }

    public void setRepos(List<?> repos) {
        this.repos = repos;
    }
}

Output will be like this :

Type of variable in classA : java.util.ArrayList
Type of data inside the list : java.lang.String
A
B

Duplicates: Get generic type of class at runtime

That example demonstrates that any list can hold objects of any classes:

    List<String> stringList = new ArrayList<>();
    List list = stringList;
    list.add(new Object());
    for (String s : stringList) {
        System.out.println(s);
    }

Only thing that you can do - is to test classes of elements if the list contains any.

Related