Quantcast
Channel: Pure-Essence.Net » instantiate
Viewing all articles
Browse latest Browse all 2

Java instaniate an abstract class… sort of…

$
0
0

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;
}


Viewing all articles
Browse latest Browse all 2

Trending Articles