-5

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?

  • 1
    Welcome to SO. What did you try so far? We are not going to do it for you. You have to come up with your own solution – D. Lawrence Dec 11 '19 at 10:15
  • 1
    `when i add HandlerC`: how? – jhamon Dec 11 '19 at 10:16
  • With the help of inheritance? Use a super class that adds the instance to the chain... – Jean-Baptiste Yunès Dec 11 '19 at 10:17
  • @D.Lawrence i know how chain of responsibility work but what i want is give class name as string then it create the instance of that class. – Ahmad Saleh Dec 11 '19 at 10:20
  • @jhamon when add the class file to my folder. – Ahmad Saleh Dec 11 '19 at 10:21
  • what folder? source folder? running app container folder? Your question is way too broad for now. Edit it to add more details on what you are doing/trying to do. – jhamon Dec 11 '19 at 10:24
  • Naming a pattern doesn't explain what **you** are doing and how **you** are implementing it.If you don't want to answer the questions of people trying to help you, maybe you are not on the right place – jhamon Dec 11 '19 at 10:42
  • @jhamon my question not about the patter. about automaic creation of the chain. when add a new handler the system will add it without changing of the chain creation code. – Ahmad Saleh Dec 11 '19 at 10:45

1 Answers1

0
    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));
    }