【问题标题】:cannot call sun.security.tools.keytool.Main from within maven test units无法从 Maven 测试单元中调用 sun.security.tools.keytool.Main
【发布时间】:2015-09-10 15:23:27
【问题描述】:

我得到(oracle jdk 8)

java.lang.IllegalArgumentException: argument type mismatch
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at ....KeyStoreCreationTest.test(KeyStoreCreationTest.java:41)

    Class<?> keytoolClazz = Class.forName("sun.security.tools.keytool.Main");
    Method mainMethod = keytoolClazz.getMethod("main", new Class[] { String[].class });
    log.info(mainMethod);
    Object[] params = new String[]{"-help"};
    mainMethod.invoke(null, params);

    mainMethod.invoke(null, new String[]{"-help"});

如果我尝试直接调用该方法,它说没有这样的包。

有什么想法吗?

日志语句输出:

public static void sun.security.tools.keytool.Main.main(java.lang.String[]) throws java.lang.Exception

【问题讨论】:

    标签: maven java-8 keytool maven-surefire-plugin


    【解决方案1】:

    Method.invoke 需要 Objects 的数组,表示(几乎)任意数量的参数。 main 方法需要一个 single 参数,该参数具有数组类型。

    所以你可以调用它使用

    mainMethod.invoke(null, new Object[]{ new String[]{"-help"} });
    

    或者,因为它是一个 varargs 方法:

    mainMethod.invoke(null, (Object)new String[]{"-help"});
    

    在后一种情况下,将其强制转换为 Object 会强制编译器将其视为单个参数,该参数将自动包装到数组中(这就是可变参数方法的意义所在)。

    请注意,您也可以在查找中使用可变参数功能:

    Method mainMethod = keytoolClazz.getMethod("main", String[].class);
    

    该类型将自动包装到一个数组中。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-08-28
      • 2020-10-15
      • 1970-01-01
      • 2021-08-30
      • 2016-09-27
      • 1970-01-01
      • 1970-01-01
      • 2022-07-08
      相关资源
      最近更新 更多