加载可选的依赖项

时间:2013-11-29 10:04:56

标签: java class reflection shared-libraries

我正在尝试加载可能在运行时不存在的依赖项。我读过一篇关于loading strategies的文章。我现在有实施问题。 我的代码目前是:

// Addition might not be available at runtime
try {
    Class Addition = Class.forName("com.thirdparty.Addition");
    com.thirdparty.Addition addition = (com.thirdparty.Addition)Addition.newInstance();
    int sum = addition.add(4,5);
    System.out.println("The result is: " + sum);
    } catch (Throwable ex) {
        System.out.println("Addition is not available");
}

此代码段在Addition类可用时有效。当课程不可用时,它不起作用:

com.thirdparty.Addition cannot be resolved to a type

我已经阅读了Class.forName方法上的javadoc,但我真的不明白如何在真正的单词中使用它。

1 个答案:

答案 0 :(得分:0)

你应该使用反射来调用add方法,如下所示:

try {
    Class Addition = Class.forName("com.thirdparty.Addition");
    Object addition = Addition.newInstance();
    Method addMethod = Addition.getMethod("add", int.class, int.class);
    Integer sum = (Integer)addMethod.invoke(addition, 4, 5);
    System.out.println("The result is: " + sum);
    } catch (Throwable ex) {
        ex.printStackTrace();
        System.out.println("Addition is not available");
}