1

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

@SuppressWarnings("unchecked")
public static <T> Class<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?

3 Answers 3

5

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.

Sign up to request clarification or add additional context in comments.

Comments

3

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);
}

1 Comment

Modern JVMs are pretty good at escape detection and will dispose of the newInstance immediately, so I wouldn't bother with caching.
2

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.

1 Comment

@finnw I agree that it probably looks cleaner with 0. This works anyway and i don't think it's has any strange issues because there is still object allocation for the array in either case and that allocation is immediately freed after we get the class reference.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.