Java - dynamically instantiate abstract subclass -


i have following abstract class

public abstract class document {   private file file;   public document(file f) {     this.file = f;   }    ...    public abstract string parse(); } 

currently, have 2 classes extend document, jsondocument , xmldocument.

in class, documentcontent, have function iterates through collection of json , xml files , calls parse() function extract content.

how can dynamically instantiate document object based on file extension detected without using conditional statement? there other file extensions added in future, want avoid need update documentcontent every time new document class type created.

you can choose use reflection or not, without reflection need design builder, like:

abstract class documentbuilder {   public abstract document build(file file); }  hashmap<string, builder> builders = new hashmap<string, builder>(); builders.put("xml", new builder(){    public build(file file) { return new xmldocument(file); }  });  builder correctbuilder = builders.get("xml"); if (correctbuilder != null)   return correctbuilder.build() 

with reflection similar use newinstance facility given reflection itself:

hashmap<string, class<? extends document>> builders = new hashmap<string, class<? extends document>>(); builders.put("xml", xmldocument.class);  try {   document document = builders.get("xml").newinstance(); } catch (...) 

Comments

Popular posts from this blog

python - Subclassed QStyledItemDelegate ignores Stylesheet -

java - HttpClient 3.1 Connection pooling vs HttpClient 4.3.2 -

SQL: Divide the sum of values in one table with the count of rows in another -