如何减少由于反射导致的picocli应用程序启动缓慢

时间:2018-09-29 12:34:52

标签: picocli

Picocli必须自省命令树。这样做需要为每个命令加载域对象类,这会减慢jvm的启动速度。

有哪些选项可以避免启动延迟? https://github.com/remkop/picocli/issues/482中描述了我提出的一种解决方案:

我正在使用反射将任何类的加载推迟到选择命令后。这样,仅加载命令类本身,最后加载实现用户请求的单个命令的类:

max-width

具体的推荐班:

abstract class BaseCommand implements Runnable {

    interface CommandExecutor {
        Object doExecute() throws Exception;
    }

    // find the CommandExecutor declared at the BaseCommand subclass.
    protected Object executeReflectively() throws Exception {
        Class<?> innerClass = getExecutorInnerClass();
        Constructor<?> ctor = innerClass.getDeclaredConstructor(getClass());
        CommandExecutor exec = (CommandExecutor) ctor.newInstance(this);
        return exec.doExecute();
    }

    private Class<?> getExecutorInnerClass() throws ClassNotFoundException {
        return getClass().getClassLoader().loadClass(getClass().getName() + "$Executor");
    }

    public void run() {
        try {
             executeReflectively();
       } catch(...){
          /// usual stuff
       }
    }
}

似乎https://github.com/remkop/picocli/issues/500可能为此提供了最终解决方案。在那之前还有哪些其他选择?

1 个答案:

答案 0 :(得分:0)

不需要任何代码更改的替代方法是使用GraalVM将基于picocli的应用程序编译为本地图像。

This article显示了如何执行此操作,并且产生的启动时间为3毫秒。

Example picocli-based app running on GraalVM