dimanche 1 février 2015

Run-time class instantiation based on external xml in Java

I have an xml file that contains data I want to parse and read into my program so i can instantiate a class.


The problem is, which class i want to instantiate wont be known until runtime.


My xml will be a little like below.


<dataitem class="FooClass"> <dataitem class="BarClass">


Classes will all share a common interface. At the moment i have Factory doing something like below.


public class FooBarFactory { FooBarInterface makeClass(String s){ if(s.equals("FooClass")){ return new FooClass(); } if(s.equals("BarClass")){ return new BarClass(); } }


In reality, there are a great many potential classes the Factory could return. Is there a way to get this sort of behaviour without having to use a conditional statement for each potential class it could be? If not, is my thinking correct or is there a better way of doing this?






Aucun commentaire:

Enregistrer un commentaire