Java Reflection calling constructor with primitive types

Viewed 36984

I have a method in my test framework that creates an instance of a class, depending on the parameters passed in:

public void test(Object... constructorArgs) throws Exception {
    Constructor<T> con;
    if (constructorArgs.length > 0) {
        Class<?>[] parameterTypes = new Class<?>[constructorArgs.length];
        for (int i = 0; i < constructorArgs.length; i++) {
            parameterTypes[i] = constructorArgs[i].getClass();  
        }
        con = clazz.getConstructor(parameterTypes);
    } else {
        con = clazz.getConstructor();
    }
}

The problem is, this doesn't work if the constructor has primitive types, as follows:

public Range(String name, int lowerBound, int upperBound) { ... }

.test("a", 1, 3);

Results in:

java.lang.NoSuchMethodException: Range.<init>(java.lang.String, java.lang.Integer, java.lang.Integer)

The primitive ints are auto-boxed in to object versions, but how do I get them back for calling the constructor?

6 Answers

To actually check if a type is a primitive or it's wrapper use:

ClassUtils.isPrimitiveOrWrapper(memberClazz)

In the case you want to check if it's a specific type take a look at this:

https://stackoverflow.com/a/27400967/2739334

In any case @Andrzej Doyle was completely right!

Related