0

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?

4

1 回答 1

3

类加载器没有创建新实例:您是在告诉VM 在此处创建一个新实例:

Object mainMethodInstance = mainClass.newInstance();

不要那样做。只需null作为静态方法调用的目标传入:

Object result = mainMethod.invoke(null, serverArgConverted);
于 2013-07-21T07:34:57.863 回答