dimanche 12 juillet 2015

load a class without knowing name in a specific folder in java

I have a java app that do some operation in a file and release output of results. and I want add a property that everyone that use my app can add his/her specific operator. and know i want to load class without knowing its name or methods.

thanks before u answer how it is possible..

this is my class and i know the class and method name that might be added:

public class PathGetter {

public static void main(String[] args) {
    try{
        String AbsolutePath = args[0];
        AbsolutePath += "\\in.txt";

        String SecondFilePath = args[1];
        SecondFilePath += "\\out.txt";

        File file = new File(SecondFilePath);
        file.createNewFile();
        FileWriter writer = new FileWriter(file);

        FileReader fr = new FileReader();
        Object newOp = null;
        String newOpSign="!@#$%^&*";
        Method m = null;

        MathOperations mathOperations = new MathOperationsImpl();

        System.out.println("Do you have new operator? ");
        Scanner scanner1 = new Scanner(System.in); 

        if(scanner1.nextBoolean()==true){
            Scanner scanner2 = new Scanner(System.in);
            System.out.println("Enter operator sign: ");
            newOpSign = scanner2.nextLine();

            File addedClass= new File("E:\\workspace\\940420\\bin");

            URI uri = addedClass.toURI();
            URL[] urls = new URL[]{uri.toURL()};

            ClassLoader classLoader = new URLClassLoader(urls);

            Class clazz = classLoader.loadClass("second.MathOperationsUpdateImpl");   \\ knowing name of class might be added!

            newOp = clazz.newInstance();    
            m = newOp.getClass().getMethod("mathOperate", String.class);  \\i know name of method that wrote in class

        }



        ArrayList<String> answer = new ArrayList<String>();

        for (int i = 0; i < fr.readFile(AbsolutePath).size(); i++) {
            if((fr.readFile(AbsolutePath).get(i)).contains(newOpSign)){

                answer.add(i,  String.valueOf(m.invoke(newOp,(fr.readFile(AbsolutePath).get(i)))));
            }
            else{
                answer.add(i, String.valueOf(mathOperations.mathOperate(fr.readFile(AbsolutePath).get(i))));
            }
        }

        for (int i = 0; i < fr.readFile(AbsolutePath).size(); i++) {
            writer.write(answer.get(i)+ "\r\n");
        }

        writer.close();

        System.out.print("Your File Successfully Created In: " + SecondFilePath);

    } catch (Exception e) {
        System.err.println("Error: " + e.getMessage());
    }
}   

}

sorry for my beginner code, i have just 2 week experience in programming.





Aucun commentaire:

Enregistrer un commentaire