geeky · non php code

Java instaniate an abstract class… sort of…

At work I had to create some test data for a junit test. The function I’m testing expects a super abstract class to be passed in and I need to test the same function for bunch of child classes. I wish I could just pass in the parent class but since it’s abstract I cannot instantiate it. I wonder if there is a way using reflection so I can instantiate the class?? Since I could not find a way, I used the following:

public void testSomeFunction() throws Exception {
	ParentData data1 = populate(ChildDataOne.class);

	ParentData data2 = populate(ChildDataTwo.class);

private static ParentData populate(Class clazz) throws Exception {
	ParentData data = clazz.newInstance();
	return data;

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s