reflection - Java Dynamic Factory -


i have half year of java experience, please excuse lack of knowledge. tried doing google searches, , have ideas on this, there few holes need fill in.

i trying create 'dynamic factory' program doing. basis of want people able insert class files folder, , loaded factory create new instances of them later.

this have right now:

import java.util.hashmap; import java.util.map;  public class kitmanager {      private map<string, class<? extends kit>> kitmap;      public kitmanager() {         kitmap = new hashmap<string, class<? extends kit>>();     }      public kit makekit(string kitname) {         try {             return kitmap.get(kitname).newinstance();         } catch (exception e) {             e.printstacktrace();             return null;         }     }    } 

now trying figure out how classes inside of folder, make sure extend kit, , insert them map have instances of them created later. stuck, cannot think of way have classes loaded map without having class names , lookup strings identified somewhere in config. idea had have static code inside each class insert hashmap, not sure how work. asking idea on how go accomplishing goal. (having folder users can input classes (that extend kit), , have classes dynamically load kitmap when program loaded)

hard give answer when requirements bit vague.

from say, create classloader pointing directory users put classes:

classloader kitclassloader = new urlclassloader("file://<path>", kitmanager.class.getclassloader()); 

to find classes, use simple directory list method, e.g. java.io.file.listfiles() (using file instance pointing correct path obviously):

file[] candidates = new file("<path>").listfiles(); 

you can use kitclassloader load class found:

kitclassloader.loadclass(classname); 

class names can derive splitting of ".class" extension files found listfiles(). after loading class, can check has default constructor , if implements kit (if doesn't, reject or display error message).

thats approach, has dire security issues (you have no idea classes do when load them), , may introduce problems dependencies (the classes load may need additional libraries?).


Comments

Popular posts from this blog

c++ - CryptStringToBinary API behavior -

c++ - Correct method for redrawing a layered window -

java.util.scanner - How to read and add only numbers to array from a text file -