mercredi 26 août 2015

How to load all compiled class from a folder?

I have a folder operators .In this folder I have compiled file(one interface operator AND 4 class that implement operator) .The purpose is load all the .class file from this folder and use in the main program . I use this statments :

    File operatorFile = new File("D:\\operators");
    URL operatorFilePath = operatorFile.toURL();          
    URL[] operatorFilePaths = new URL[]{operatorFilePath};
    ClassLoader operatorsLoader = new URLClassLoader(operatorFilePaths);

 //Plus,Minus,Multiply,Divide are classes that implement operator interface
   Class[] operatorClass = new Class[]{ operatorsLoader.loadClass("Plus"), operatorsLoader.loadClass("Minus"),operatorsLoader.loadClass("Multiply") , operatorsLoader.loadClass("Divide") };

Then I use this statment to call .class file methods :

Method methodsInOperator;
Object instance;
String operatorSign;

for(Class operatorCls : operatorClass)
{
   instance = operatorCls.newInstance();
    methodsInOperator = operatorCls.getMethod("getSign", null); 
    operatorSign = (String)methodsInOperator.invoke(instance, null);
                    if(operatorSign.equals(elementInExpression[2]))
                    {
    methodsInOperator = operatorCls.getMethod("calculate", new Class[] { double.class, double.class } ); 
                        output =(double)methodsInOperator.invoke(instance, firstNumber, secondNumber);  
                    }
                }

But below statment dose not work dynamically and if we put another .class file to operators folder program stop working .

Class[] operatorClass = new Class[]{ operatorsLoader.loadClass("Plus"), operatorsLoader.loadClass("Minus"),operatorsLoader.loadClass("Multiply") , operatorsLoader.loadClass("Divide") };

My purpose is to load all classes dynamically and check if they implement operator and according to getSing() method choose the best class .Can anyone help me?





Aucun commentaire:

Enregistrer un commentaire