Search code examples
javaclassloader

Java Classloaders - Invoking a static method inside a private class


I would like to invoke a static method inside of a private class in Java using classloaders.

This is a short version of my classloader that I have been using.

URL[] jarURLArray = { server.lan.serverJAR().toURL() };
URLClassLoader serverClassLoader = new URLClassLoader(jarURLArray,  this.getClass().getClassLoader());
Class mainClass = Class.forName("com.packagename.someclass", true, serverClassLoader);
Class sampleArgClass[] = { (new String[1]).getClass() };
Method mainMethod = mainClass.getDeclaredMethod("getSimplifiedName", sampleArgClass);
Object mainMethodInstance = mainClass.newInstance();
Object serverArgConverted[] = { args };
Object result = mainMethod.invoke(mainMethodInstance, serverArgConverted);

This code loads classes from a jar file and I am able to invoke classes under normal circumstances.

When I have a class, such as this one:

public final class someClass
{
private static Server server;

/**
 * Static class cannot be initialized.
 */
private someClass()
{
}

public static int someValue()
{
    return someValue;
}

I am unable to reach the someValue() method because of how the classloader creates new instances of the class, which, is not possible because it has a private constructor.

How can I reach the someValue method using a classloader?


Solution

  • The classloader isn't creating a new instance: you're telling the VM to create a new instance here:

    Object mainMethodInstance = mainClass.newInstance();
    

    Don't do that. Just pass in null as the target of the static method call:

    Object result = mainMethod.invoke(null, serverArgConverted);