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

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-11 12:11:13

问题


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.

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");   \\I don't know the class name might be added

            newOp = clazz.newInstance();    
            m = newOp.getClass().getMethod("mathOperate", String.class); \\I don't know the method name in added 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());
    }
}   
}

回答1:


Summery of the comments to give final answer:

1: If you don't know the class name, you can use File to get the content of the directory:

File d = new File("<knowDirectory>");
File[] f = d.listFiles();

Of course, there should be only one .class file in the directory.

2.: So you know the name and path of the class file. Load it with

Class c = Class.forName("<classname>").

Than you can get all available methods via reflection, too:

Methods[] m = c.getMethods();

3(A).: If you don't know the name of the method you want to invoke, but its signature (ie, return type and parameters), you can use m.getReturnType() and m.getParameterTypes() to look for a method with the designated signature. If there are multiple, there is no way to distinguish them. If there is only a single method with the signature just use it (call by reflection). Something like this (for return type Double and single parameter String):

Class<?>[] params = m.getParameterTypes();
Class<?> r = m.getReturnType();
if(r.getName().equals(Double.class.getName())
   && params.length == 1
   && params[0].getName().equals(String.class.getName()))
{
   // invoke
}

3(B).: If you force the user to implement an abstract class (or interface), hence, you know the name of the method to be implemented, load the class and cast it to the interface:

Class childClass = Class.forName("DerivedClassName");
MyAbstractClass userOperator = (MyAbstractClass)childClass.newInstance();


来源:https://stackoverflow.com/questions/31365262/load-a-class-without-knowing-name-in-a-specific-folder-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!