Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Reflection calling constructor with primitive types

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?

like image 747
Steve Avatar asked Oct 13 '10 15:10

Steve


People also ask

Which method is used to get constructor using reflection?

The getConstructors() method is used to get the public constructors of the class to which an object belongs. The getMethods() method is used to get the public methods of the class to which an object belongs. We can invoke a method through reflection if we know its name and parameter types.

What are reflections in Java is it compile time or runtime?

Reflection is a language's ability to inspect and dynamically call classes, methods, attributes, etc. at runtime.

Does Java support reflection?

Reflection is a feature in the Java programming language. It allows an executing Java program to examine or "introspect" upon itself, and manipulate internal properties of the program. For example, it's possible for a Java class to obtain the names of all its members and display them.

What is reflection in Java serialization?

Java serialization uses reflection to scrape all necessary data from the object's fields, including private and final fields. If a field contains an object, that object is serialized recursively. Even though you might have getters and setters, these functions are not used when serializing an object in Java.


1 Answers

Use Integer.TYPE instead of Integer.class.

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

You can also use int.class. It's a shortcut for Integer.TYPE. Not only classes, even for primitive types you can say type.class in Java.

like image 151
Andrzej Doyle Avatar answered Sep 21 '22 07:09

Andrzej Doyle