从另一个 Jar 文件获取字段

Getting fields from another Jar File

我尝试从外部 jar 中读取字段。我们将外部文件命名为:'Data.jar'.

Data.jar 包含一个名为 Constants 的 class 和一些 public、静态、最终字段。例如:

public static final String string1 = "Test"; 
public static final int integer1 = 1;

如何访问外部文件以获取字段 string1 和 integer1 的值?是否可以使用反射?我知道外部 jar 和结构。

编辑:

外部 jars 结构是我当前项目的旧版本。所以我使用 URLClassLoader 并调用 class Constants,我将获得当前项目的值,而不是 jars 的值。那么有没有办法只调用外部 jar classes?

解法:

    public Object getValueFromExternalJar(String className, String fieldName) throws MalformedURLException
    {
       Object val = null;
       // calling the external jar
       URLClassLoader cL = new URLClassLoader(new URL[] { jarURL }, null);
//the null is very important, if the jar is structural identical to this project
       try
       {
          // define the class(within the package)
          Class<?> clazz = cL.loadClass(className);
          // defining the field by its name
          Field field = clazz.getField(fieldName);
          field.setAccessible(true);
          // get the Target datatype
          Class<?> targetType = field.getType();
          Object objectValue = targetType.newInstance();
          // read the value
          val = field.get(objectValue);
       }
       catch (ClassNotFoundException | NoSuchFieldException | SecurityException | IllegalAccessException
             | InstantiationException e)
       {
          LOGGER.log(Level.SEVERE, "An error while accessing an external jar appears", e);
       }
       finally
       {
          try
          {
             cL.close();
          }
          catch (Exception e)
          {
          }
       }
       return val;
    }

根据您的描述使用 URLClassLoader 的一些示例代码,如 :

URLClassLoader cl = new URLClassLoader(new URL[] {new File("Data.jar").toURI().toURL()});
Class<?> clazz = cl.loadClass("Constants");
String string1 = (String) clazz.getField("string1").get(null);
int integer1 = clazz.getField("integer1").getInt(null);

我想您必须更改示例以匹配您的结构。