简体   繁体   中英

Create a list of dynamic type in Java

I am trying to create a List (well, in fact several) object without knowing in advance it's type, and passing to the funcion I want to create those lists a parameter of type Class<?> , so for exmaple it is working file if I return tickr1, but when I try to create a second list and add all elements of this second list it is complaining:

method java.util.Collection.addAll(java.util.Collection<? extends capture#2 of?>) is not applicable

Is there a way to create the list any way similar to

List<clazz.clazz.getTypeName()> tickr1...

At the end I've used List and obtained the desired results, but, is there a better way?

public class Crawler {

    private List<?> metacrawler(String level1, String level2, Class<?> clazz, String resource) throws IOException {
        InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream(resource);
        Reader inr = new InputStreamReader(in);
        String json = CharStreams.toString(inr);
        Object glue = JsonPath.read(json, "$."+level1+"[*]."+level2);
        ObjectMapper om = new ObjectMapper();

        List<?> tickr = om.readValue(glue.toString(),
                                    om.getTypeFactory().constructCollectionType(List.class, clazz));
        List<?> tickr2 = om.readValue(glue.toString(),
                                    om.getTypeFactory().constructCollectionType(List.class, clazz));
        tickr.addAll(tickr2);

        return tickr;
    }

    public List<ObjectType1> getObjectsOfType1() throws IOException {
        return (List<ObjectType1>)metacrawler("firstlevel", "secondlevel", ObjectType1.class, "1.json");
    }
}

You can create something like this:

    public static void main(String[] args) {
        List<String> list = (List<String>) metacrawler(String.class);
        System.out.println(list);
    }

    private static <T> List<?> metacrawler(T clazz) {
        List<T> list = new ArrayList<>();
        list.add((T) Arrays.asList("test1", "generic"));
        list.add((T) Arrays.asList("test2", "generic"));
        return list;
    }

, output

[[test1, generic], [test2, generic]]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM