gpt4 book ai didi

java - 从 JAR 文件中的类获取值

转载 作者:太空宇宙 更新时间:2023-11-04 11:01:20 25 4
gpt4 key购买 nike

我想在 JAR 中运行一个方法,该方法将类似于 public static SomeType getValue()

我尝试使用反射,看起来没问题:

URLClassLoader classLoader = new URLClassLoader(new URL[]{jarFile.toURI().toURL()}, Main.class.getClassLoader());
Class targetClass = classLoader.loadClass("some.package.TargetClass");
Class targetType = classLoader.loadClass("some.package.SomeType");
Method getValueMethod = targetClass.getMethod("getValue");

但是在获得这样的返回值时:

targetType value = targetClass.cast(getValueMethod.invoke(null));

value 的类型不能是 targetType,不是吗?但是,类型 SomeType 在 JAR 文件中,所以我不能像 SomeType value = ~~

那么,如何正确获取getValue()的值并访问其数据呢?

最佳答案

使用接口(interface)限制返回值。

如果返回值没有限制,那么你对其进行操作就说明你已经了解了。那么你的“动态加载”是什么意思?

抽象出一个普通的接口(interface)SomeInterface,然后

SomeInterface value = targetClass.cast(getValueMethod.invoke(null));

其他代码仅适用于SomeInterface,但不需要知道它实际是什么。这是界面的力量。

关于java - 从 JAR 文件中的类获取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46864619/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com