i have 8 handler class, is there a way i can create the chain dynamically in java?
What I mean, if I have two classes right now like:
HandlerA
HandlerB
HandlerChain
HanddlerChain will create the chain, HandlerA->HandlerB, (using loop read all class names from the folder)
when i add HandlerC then it is automatically add without any interaction and the chain become, HandlerA->HandlerB->HandlerC.
--------------------------------------------------------
So if I had String className = "HandlerA"
What is the way i make instance of HandlerA.class using the privaice String?
File folder = new File("JavaClassesPath");
ArrayList<String> all = new ArrayList<>();
for (final File fileEntry : folder.listFiles()) {
if (!fileEntry.isDirectory()) {
all.add(fileEntry.getName().substring(0, fileEntry.getName().lastIndexOf('.')));
}
}
String className = "PackageName";
for (String s: all) {
if (!s.equals("AbstractClassName")) {
Class<?> clazz = Class.forName(className + '.' + s);
Constructor<?> ctor = clazz.getConstructor();
Object object = ctor.newInstance();
allHandlers.add((RequestHandler) object);
}
}
for(int i=0; i<allHandlers.size()-1; i++){
allHandlers.get(i).setNextHandler(allHandlers.get(i+1));
}