[英]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. 我想使用类加载器在Java的私有类内部调用静态方法。
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. 这段代码从jar文件加载类,在正常情况下,我可以调用类。
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. 由于类加载器如何创建类的新实例,我无法到达someValue()方法,这是不可能的,因为它具有私有构造函数。
How can I reach the someValue method using a classloader? 如何使用类加载器到达someValue方法?
The classloader isn't creating a new instance: you're telling the VM to create a new instance here: 类加载器没有创建新实例:您要在这里告诉 VM创建新实例:
Object mainMethodInstance = mainClass.newInstance();
Don't do that. 不要那样做 Just pass in null
as the target of the static method call: 只需传入null
作为静态方法调用的目标即可:
Object result = mainMethod.invoke(null, serverArgConverted);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.