以下是一个示例Java程序,通过配置文件获取jar包地址和名字,并加载程序中判断地址末尾是否包含斜杠,自动拼接jar包地址。获取jar包时判断是否存在,调用jar包时可以指定参数,jar包无需指定方法。

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

public class JarLoaderExample {
    public static void main(String[] args) {
        try {
            // 从配置文件中读取jar包地址和名字
            Properties properties = new Properties();
            FileInputStream fis = new FileInputStream("config.properties");
            properties.load(fis);
            String jarPath = properties.getProperty("jarPath");
            String jarName = properties.getProperty("jarName");
            
            // 判断jar包地址是否包含斜杠,如果不包含,则自动拼接斜杠
            if (!jarPath.endsWith(File.separator)) {
                jarPath += File.separator;
            }
            
            // 拼接完整的jar包路径
            String jarFilePath = jarPath + jarName;
            
            // 检查jar包是否存在
            File jarFile = new File(jarFilePath);
            if (!jarFile.exists()) {
                throw new RuntimeException("Jar file does not exist: " + jarFilePath);
            }
            
            // 使用URLClassLoader加载jar包
            URLClassLoader classLoader = new URLClassLoader(new URL[]{jarFile.toURI().toURL()});
            
            // 加载jar包中的类
            Class<?> loadedClass = classLoader.loadClass("com.example.MyClass");
            
            // 可以根据需要调用jar包中的方法,这里只是示例
            Method method = loadedClass.getMethod("myMethod", String.class);
            Object result = method.invoke(null, "Hello");
            
            System.out.println("Result: " + result);
            
            // 关闭URLClassLoader
            classLoader.close();
        } catch (IOException | ClassNotFoundException | NoSuchMethodException | SecurityException | ReflectiveOperationException e) {
            e.printStackTrace();
        }
    }
}

在上述示例中,首先从配置文件中读取jar包地址和名字。然后,判断地址末尾是否包含斜杠,如果不包含,则自动拼接斜杠。接下来,检查jar包是否存在,如果不存在,则抛出异常。然后,使用URLClassLoader加载jar包,并加载jar包中的类。可以根据需要调用jar包中的方法,这里只是示例调用了一个名为"myMethod"的方法,并传递了一个参数"Hello"。最后,关闭URLClassLoader。

请注意,示例中的配置文件名为"config.properties",需要与示例代码放在同一目录下,并在配置文件中添加以下内容:

jarPath=/path/to/jar/
jarName=myjar.jar

将"/path/to/jar/"替换为实际的jar包路径


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

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