3

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) {}
Interlated
  • 5,108
  • 6
  • 48
  • 79
  • Good question - thanks for formatting it nicely, and giving a nice, neat example. Always helps =) – Addison Oct 20 '16 at 00:44

1 Answers1

4

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

Community
  • 1
  • 1
Addison
  • 7,322
  • 2
  • 39
  • 55
  • If you think it's a duplicate, please just flag to close as such. Eventually, [when you have 3k reputation](http://stackoverflow.com/help/privileges/close-questions), you'll also be able to vote. – Sotirios Delimanolis Oct 20 '16 at 02:28
  • I'll do that in the future, @SotiriosDelimanolis. I didn't want to go flag-happy now that I've just earned the privilege to. Besides, I'd gone to the trouble of answering it before I even found the SO solution (after a second search). – Addison Oct 20 '16 at 02:32