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?
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.
Reflection is a language's ability to inspect and dynamically call classes, methods, attributes, etc. at runtime.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With