Interlated Interlated - 1 year ago 96
Java Question

How do I call a constructor in java via reflection?

I have am dumping CSV via jackson. I have a couple of mapping classes and want to pass the mapping class to the CSV export method.

I have an abstract class, extended it to each of the csv column formats. I pass the name of the class to the export function then want to map the data via the constructor for the class and dump it as CSV.

All fine until I get to creating the class that does the mapping and is to be exported.

Invocation exception/Invalid number of parameters exception.

protected String mapTransactionsToCSV(List<Object[]> results, String rowClassName)
Class rowClass = Class.forName(rowClassName);
for (Object[] component : results)
VehicleAbstract vehicle = (VehicleAbstract) rowClass.getDeclaredConstructor(Object[].class).newInstance(component);

My specific class (and abstract class, which I just copied to try). has 2 constructors

public Bus() {}
public Bus(Object[] component) {}

Answer Source

See Problem with constructing class using reflection and array arguments

The problem is that newInstance already takes an array of objects. You need to wrap your object array in another array. Something like this:

component = {component}; // Wrap in a new object array
VehicleAbstract vehicle  = (VehicleAbstract) rowClass.getDeclaredConstructor(Object[].class).newInstance(component);

This is the reason that you're getting an invalid number of parameters - you're passing each item in that object array as a separate parameter, instead of one parameter (the array of objects).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download