Java程序示例通过配置文件获取jar包地址、名字使用固定参数调用jar包jar包无需指定main方法
以下是一个示例的Java程序,它通过配置文件获取jar包的地址和名称,并使用固定参数调用该jar包。这里假设配置文件的格式为properties格式。
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;
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/imtY 著作权归作者所有。请勿转载和采集!