开发者

Class.getArrayType in Java?

I use the following trick to get the array type of a specific class:

@SuppressWarnings("unchecked")
public static <T> Cla开发者_StackOverflowss<T[]> getArrayType(Class<T> componentType) {
    String arrayClassName = "[L" + componentType.getName() + ";";
    try {
        return (Class<T[]>) Class.forName(arrayClassName);
    } catch (ClassNotFoundException e) {
        throw new UnexpectedException("Can't get the array type for " + componentType, e);
    }
}

But, is there any more elegant way to get this?


Perhaps using Array.newInstance(), which returns an array of a given type.

Doing something like:

return Array.newInstance(someClass, 0).getClass()

Might get you what you want.

Hope that helps.


I would do the same as Zach L but memoize the result:

import java.lang.reflect.Array;
import java.util.concurrent.ConcurrentMap;
import com.google.common.base.Function;
import com.google.common.collect.MapMaker;

// ...

static Function<Class<?>, Class<?>> TO_ARRAY_FUNC =
    new Function<Class<?>, Class<?>>() {
        @Override
        public Class<?> apply(Class<?> from) {
            return Array.newInstance(from, 0).getClass();
        }
    };

static ConcurrentMap<Class<?>, Class<?>> ARRAY_TYPE_MAP =
    new MapMaker().weakKeys()
                  .weakValues()
                  .makeComputingMap(TO_ARRAY_FUNC);

@SuppressWarnings("unchecked")
public static <T>Class<T[]> getArrayType(Class<T> componentType) {
    return (Class<T[]>) ARRAY_TYPE_MAP.get(componentType);
}


Try this:

@SuppressWarnings({"unchecked"})
public static <T> Class<T[]> getArrayType(Class<T> componentType) {
    return (Class<T[]>) Array.newInstance(componentType, 1).getClass(); 
}

You can't escape the warning but it is shorter and better.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜