简体   繁体   English

使用ClassLoader时如何将参数传递给jar?

[英]How can I pass parameters to a jar, whilst using a ClassLoader?

Here's my code 这是我的代码

package serverloader;

import java.net.URL;
import java.net.URLClassLoader;

public class ServerLoader {

    public void initiate(String[] arguments) throws Exception {
        System.out.println("Initiating...");
        URL link = new URL("link");
        URLClassLoader classLoader = new URLClassLoader(new URL[]{link});
        Object o = classLoader.loadClass("class.MyClass").newInstance();
        System.out.println("Loaded, starting...");
    }

}

This is the loader to load my actual application, but for some reason it's not starting up and I believe it's because there are parameters that are needed to launch the application that's being loaded here, so how do I pass the parameters, which are here 这是加载程序,用于加载我的实际应用程序,但是由于某种原因,它没有启动,我相信这是因为启动此处要加载的应用程序需要一些参数,因此如何传递参数,这些参数在此处

String[] arguments

to the jar that is being loaded by the ClassLoader? 到由ClassLoader加载的jar中?

Kind of, you need to use reflection to get the constructor which meets your needs, something like... 有点,您需要使用反射来获取满足您需求的构造函数,例如...

Class[] clazz = classLoader.loadClass("class.MyClass");
Constructor constructor = clazz.getConstructor(String[].class);

Once you have the constructor, you can create a new instance of the class using Constructor#newInstance ... 一旦有了构造函数,就可以使用Constructor#newInstance创建类的新实例。

Object o = constructor.newInstance(arguments);

As an example... 举个例子...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM