在不知道Java中特定文件夹中名称的情况下加载类 [英] load a class without knowing name in a specific folder in java

查看:59
本文介绍了在不知道Java中特定文件夹中名称的情况下加载类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个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.

这是我的类,我知道可以添加的类和方法名称:

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


推荐答案

总结意见以给出最终答案:

Summery of the comments to give final answer:

1:如果您不知道班级名称,则可以使用要获取目录内容的文件:

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();

当然,应该只有一个 .class 目录中的文件。

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

2。:这样您就知道了类文件的名称和路径。

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)。::如果您不知道名字要调用的方法的类型(但具有其签名(即返回类型和参数)),可以使用 m.getReturnType() m。 getParameterTypes()查找具有指定签名的方法。如果有多个,则无法区分它们。如果只有一个带有签名的方法,请使用它(通过反射调用)。诸如此类(对于返回类型 Double 和单个参数 String ):

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)。:。如果您强迫用户实现抽象类(或接口),则您知道要实现的方法的名称,加载该类并将其转换为接口:

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();

这篇关于在不知道Java中特定文件夹中名称的情况下加载类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆