以下是一个示例的 Java 程序,它通过配置文件获取 JAR 包的地址和名称,并使用固定参数调用该 JAR 包。这里假设配置文件的格式为 properties 格式。

import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;
import java.net.URL;
import java.net.URLClassLoader;
import java.lang.reflect.Method;
import java.lang.reflect.InvocationTargetException;

public class JarLoader {

    public static void main(String[] args) {
        Properties properties = new Properties();
        try {
            // 加载配置文件
            properties.load(new FileInputStream('config.properties'));
            
            // 获取 JAR 包的地址和名称
            String jarPath = properties.getProperty('jar.path');
            String jarName = properties.getProperty('jar.name');
            
            // 创建一个新的 ClassLoader,用于加载 JAR 包
            URLClassLoader classLoader = new URLClassLoader(new URL[]{new File(jarPath + '/' + jarName).toURI().toURL()});
            
            // 加载 JAR 包中的类
            Class<?> mainClass = classLoader.loadClass(jarName.substring(0, jarName.lastIndexOf('.')));
            
            // 调用指定方法
            Method method = mainClass.getMethod('main', String[].class);
            method.invoke(null, new Object[]{args});
            
        } catch (IOException | ClassNotFoundException | NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
            e.printStackTrace();
        }
    }
}

在上述示例中,我们假设配置文件名为'config.properties',它的内容如下:

jar.path=/path/to/jar
jar.name=myjar.jar

其中,'jar.path' 是 JAR 包的存放路径,'jar.name' 是 JAR 包的名称。

请将上述示例代码保存为'JarLoader.java' 文件,并在同目录下创建配置文件'config.properties',然后将实际的 JAR 包地址和名称填写到配置文件中。

运行'JarLoader' 类,它将加载配置文件中指定的 JAR 包,并调用该 JAR 包中的指定方法。


原文地址: http://www.cveoy.top/t/topic/p4ua 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录