java - Any way to have a method that create new instances of a class passed by parameter? -
i creating tests in have create lists send object under test. in order create lists, have method called createentitieslist
, in send number of elements in list , receive list filled elements (with valid, random generated values). basic, able create lists of different types, instance
list<professor> list = createentitylist(professor.class); list<student> list = createentitylist(student.class);
of course professor , students have different attributes fill out.
my current method one:
private <t> list<t> getentitylist(class<t> entitytype, int numberofitems) { list<t> entities = new arraylist<t>(); (int = 0; < numberofitems; i++) { if (entitytype.equals(professorentity.class)) { entities.add((t) createprofessorentity(i)); } else { throw new unsupportedoperationexception("not yet implemented"); } } return entities; } @suppresswarnings("unchecked") private <t> t createprofessorentity(int index) { professorentity entity = new professorentity(); entity.settitle(string.format("title %s", index)); entity.setnamecompany); return (t) entity; }
ok, works, feel didn't achieved goal, because have create new method , "if" statement each new type of class want create. on other side, not see improvements make required less effort.
is there way can improve code able call 1 method create entities of desired type reduce effort add new supported class?
ps: effort not big, learn because useful in future.
yes, can. start defining interface:
public interface entitycreator<t> { t create(int index); }
and pass instance of interface method:
private <t> list<t> getentitylist(entitycreator<t> creator, int numberofitems) { list<t> entities = new arraylist<t>(); (int = 0; < numberofitems; i++) { entities.add(creator.create(i)); } return entities; }
then, create 10 professor entities:
list<professorentity> list = getentitylist(this::createprofessorentity, 10);
if you're not under java 8 yet, you'll have use inner classes:
list<professorentity> list = getentitylist(new entitycreator<professorentity>() { @override public professorentity create(int index) { return createprofessorentity(i); } }, 10);
Comments
Post a Comment