I try to read fields from an external jar. We name the external File: 'Data.jar'.
Data.jar contains a class called Constants with some public, static, final fields. For example:
public static final String string1 = "Test";
public static final int integer1 = 1;
How can I access the external file in order to get the value of the fields string1 and integer1? Is it possible to use reflections? I know the external jar and the structure.
Edit:
The external jars structure is an older version of my current project. So I use the URLClassLoader and call the class Constants, I will get the value of my current project, and not the jars one. So is there a way to only call the external jars classes?
Solution:
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;
}
Some example code using an URLClassLoader based on your description, as dan1st suggested:
URLClassLoader cl = new URLClassLoader(new URL[] {new File("Data.jar").toURI().toURL()}, ClassLoader.getPlatformClassLoader());
Class<?> clazz = cl.loadClass("Constants");
String string1 = (String) clazz.getField("string1").get(null);
int integer1 = clazz.getField("integer1").getInt(null);
I guess you have to change the example to match your structure.