【问题标题】:Casting to a jar class投射到 jar 类
【发布时间】:2014-08-01 10:27:23
【问题描述】:

我有一个 jar 文件 CallMe.jar,其中包含一个实现接口 CallInterface.class 的 mainClass CallMe.class。

从另一个应用程序我访问 CallMe.jar ,然后创建一个 CallMe.class 实例(我使用了专门用于从 jar 文件加载类的特殊类,您可以在那里找到:http://www.javaworld.com/article/2077572/learn-java/java-tip-70--create-objects-from-jar-files-.html)。

这是我的代码:

String jarPath = "/path/to/CallMe.jar";
String mainClass = "callme.CallMe";
JarClassLoader jarLoader = new JarClassLoader(jarPath); // Loads the jar
Class c = jarLoader.loadClass(mainClass, true); // Loads the specified class inside the jar.
Object jarObject = c.newInstance(); // Creates an instance of this mainClass CallMe

由于 mainClass CallMe.class 实现了 CallInterface.class 并覆盖了方法 interfaceMethod(),我想通过将 CallInterface 强制转换为我的对象来调用此方法。但为此,我似乎需要在我当前的应用程序中导入这个类。

让我们考虑一下 CallInterface 可以位于我的 jar 的任何包中: CallMe.jar -> any.package.CallInterface.class -> callme.CallMe.class

在我当前的应用程序项目中,我将 CallInterface 放在不同的包中:appli.jarLoader.CallInterface.class

如果我假设两个 CallInterface.class 类是相同的(但可能在不同的包中),我如何引用(转换)jar 中的类?

我目前的测试代码如下:

if( jarObject instanceof appli.jarLoader.CallInterface) { // The CallInterface in my application
    Print.str(DEBUGGING, "jarObject is instance!");
  appli.jarLoader.CallInterface ci = (appli.jarLoader.CallInterface) jarObject;
  ci.interfaceMethod();
}
else {
  Print.str(DEBUGGING, "jarObject not instance...");
}

未验证的条件。当我尝试这个时:

Object appliObject = new Appli(); // implements appli.jarLoader.CallInterface 

if(appliObject instanceof appli.jarLoader.CallInterface) {
    Print.str(DEBUGGING, "appliObject is instance!");
  appli.jarLoader.CallInterface ci = (appli.jarLoader.CallInterface) appliObject;
  ci.interfaceMethod();
}
else {
    Print.str(DEBUGGING, "appliObject is not instance...");
}

在这种情况下,条件得到验证,我可以访问覆盖的接口方法。

如何在jar文件中访问我的实现类中的接口方法?如何使用 ClassInterface 成功转换我的 jarObject ?


编辑 1

我的想法是我的应用程序只知道 ClassInterface 而对实现类一无所知,这意味着我不能只硬编码实现类

【问题讨论】:

  • “如果我假设两个 CallInterface.class 类是相同的(但可能在不同的包中),我如何引用(转换)jar 中的那个” - 通过导入类它在罐子里吗?
  • 我想在运行时加载类,不知道是否可以在运行时导入。

标签: java interface casting executable-jar instanceof


【解决方案1】:

如果您加载的jarObject 实现any.package.CallInterface,我假设将此对象转换为appli.jarLoader.CallInterface 将导致运行时转换异常。

如果你想将对象投射到 jar 中打包的接口,你必须将它也添加到你的项目中。

如果您确定要调用的方法的签名(名称 + 参数列表),则可以使用反射来调用您的方法:

Method m=jarObject.getClass().getMethod("methodName",Class<?>...);
m.invoke(jarObject, ...);

【讨论】:

    猜你喜欢
    • 2017-03-17
    • 1970-01-01
    • 2010-10-14
    • 2021-02-20
    • 1970-01-01
    • 2023-01-20
    • 2020-10-03
    • 2014-04-06
    • 1970-01-01
    相关资源
    最近更新 更多