Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I call a constructor in java via reflection? [duplicate]

I 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);
    csv.append(mapper.writer(schema).writeValueAsString(vehicle));
  }
}

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

public Bus() {} 
public Bus(Object[] component) {}
like image 717
Interlated Avatar asked Aug 27 '26 06:08

Interlated


1 Answers

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).

like image 152
Addison Avatar answered Aug 28 '26 19:08

Addison



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!