简体   繁体   中英

How to convert a list of Class objects into an array?

I have some Class objects in a List that I would like to convert into an array. Below is my code:

private static Class<?>[] getClasses(final Object[] params) {
    List<Class<?>> classList = new ArrayList<>();

    for (final Object param : params) {
        classList.add(param.getClass());
    }

    return (Class<?>[]) classList.toArray();
}

I understand toArray() returns an Object[]. Is there a way to avoid the cast?

You can just create a new array and put each element in, one by one:

Class<?>[] classes = new Class<?>[classList.size()];
for (int i = 0 ; i < classList.size() ; i++) {
    classes[i] = classList.get(i);
}

Or, rewrite the whole method without using the list:

    private static Class<?>[] getClasses(final Object[] params) {
        Class<?>[] classList = new Class<?>[params.length];

        for (int i = 0 ; i < classList.length ; i++) {
            classList[i] = params[i].getClass();
        }

        return classList;
    }

您可以将toArray方法与数组一起用作参数:

return classList.toArray(new Class<?>[classList.size()]);

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