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);
	//..test..

	ParentData data2 = populate(ChildDataTwo.class);
	//..test..
}

private static ParentData populate(Class clazz) throws Exception {
	ParentData data = clazz.newInstance();
	data.setProperty1("1");
	data.setProperty2("2");
	data.setProperty3("3");
	data.setProperty4("4");
	data.setProperty5("5");
	return data;
}

Leave a Reply

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

WordPress.com Logo

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

Facebook photo

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

Connecting to %s