views:

43

answers:

3

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?

+2  A: 

Use Integer.TYPE instead of Integer.class.

As per the Javadocs, this is "The Class instance representing the primitive type int."

Andrzej Doyle
int.class is a shortcut for Integer.TYPE, for any, even primitive type in Java you can write: type.class
iirekm
+1  A: 

To reference primitive types use, for example:

Integer.TYPE;

You will need to know which arguments passed into your method are primitive values. You can do this with:

object.getClass().isPrimitive()
Plaudit Design - Web Design
+1  A: 

If primitive int value is autoboxed into Integer object, it's not primitive anymore. You can't tell from Integer instance whether it was int at some point.

I would suggest passing two arrays into test method: one with types and another with values. It'll also remove ambiguity if you have a constructor MyClass(Object) and pass string value (getConstructor would be looking for String constructor).
Also, you can't tell expected parameter type if parameter value is null.

Nikita Rybak
`if primitive int value is autoboxed into Integer object, it's not primitive anymore. You can't tell from Integer instance whether it was int at some point` didn't get your this point with the question asked. if a primitive is boxed to Integer than why it doesn't resolve to var args
org.life.java
@org.life.java What do you mean, _"doesn't resolve to var args"_ ? The error is because constructor can't be found. Vararg part works smoothly, _int_ is converted into _Integer_ for second and third elements of _constructorArgs_ array (for the simple reason that _int_ can't ba a part of _Object[]_).
Nikita Rybak
ow... Sorry misunderstood Question . still Q. is unclear:)
org.life.java