Take the 2-minute tour ×

I have basic knowledge of Java's reflection API - therefore, this is not only a question of how, it's a question of whether it's possible and whether I'm going about a solution the best way.

We're doing some acceptance testing of multiple, interrelated projects; each of these projects retrieve data from a MongoDB store using an in-house abstraction API. To facilitate this testing, each component needs some pre-loaded data to be available in the database.

I'm building a command-line tool to accept a DTO (pre-compiled class binary), for loading of multiple instances using the morphia ORM library. I would like each member of our team to be able to run the generator passing in via cli their DTO (in jar or directory form), and a file (csv or otherwise) for instantiating a desired amount of records.

I have the class loading working fine with URLClassLoader. Now I'm trying to instantiate an instance of this class using data from a file.

Is this possible? Would serialized objects be a better approach?

share|improve this question

2 Answers 2

up vote 3 down vote accepted

That's perfectly possible using the Java Reflection API :

  • Load Class instance by name (Class.forName(className), you don't really need the ClassLoader instance)
  • Grab Constructor instance of constructors have parameters and invoke newInstance(Object... args) on this constructor instance to create an instance of your DTO class.
  • Invoke getDeclaredFields() on your Class instance and iterate over them to set their values (field.set(instance, value)). Make sure to invoke field.setAccessible(true) to be able to access private fields.
share|improve this answer
I'm using URLClassLoader because it accepts an array of URL which enables me to load a class (using File) external to my applications jar file; unless you can think of a nicer way? –  wulfgar.pro Oct 29 '11 at 13:33
No that works if you want to test classes in JAR files that aren't in your codebase paths. –  user1016441 Nov 2 '11 at 17:36

If by "serialized objects" you mean canned instances, then no, by loading properties from a text file you allow much easier tweaking of test data (if that's a goal), including the number of objects.

But sure, it's possible; unmarshal the data from the input file and use it to initialize or construct the object in question like you would in regular code.

share|improve this answer
looks like yaml might be a good solution for creating serialized instances that are readily tweaked. –  wulfgar.pro Oct 30 '11 at 11:36

Your Answer


