[英]How to run the method from final class with private constructor?
How to run the method foo() in class A without any changes on this class 如何在A类中运行方法foo()而不对此类进行任何更改
public final class A{
private A(){
System.exit(0);
}
public void foo(){
System.out.println("from foo");
}
}
Without doing something like using reflection or bytecode manipulation to mess with accessibility... 没有做像使用反射或字节码操作来搞乱可访问性......
The "right" way to do this is to get an instance of the class some other way. 执行此操作的“正确”方法是以其他方式获取类的实例。 For example, if there's a static factory method or pre-made instances that you can access.
例如,如果存在静态工厂方法或可以访问的预制实例。 The reason for having a private constructor like this is to control construction of the class.
拥有这样的私有构造函数的原因是控制类的构造。 (For example, enum implementations have a private constructor so that you don't create additional instances beyond the static ones supplied.)
(例如,枚举实现具有私有构造函数,因此除了提供的静态构造之外,您不会创建其他实例。)
If you side-step this then someone (either you or the original class author) is doing something wrong. 如果你支持这一点,那么有人 (你或者是原作者)做错了什么。
You can create an instance of a class without calling the constructor. 您可以在不调用构造函数的情况下创建类的实例。 See this question: Is it possible to create an instance of an object in Java without calling the constructor?
看到这个问题: 是否可以在不调用构造函数的情况下在Java中创建对象的实例?
You can use objenesis to do this for you. 您可以使用objenesis为您执行此操作。 Once you've got an instance of
A
without calling the constructor, calling foo
is easy. 一旦你有一个
A
的实例而没有调用构造函数,调用foo
很容易。
You can alter the byte code before it is loaded by the jvm. 您可以在jvm加载之前更改字节代码。 Here's a place to start: http://www.ibm.com/developerworks/java/library/j-dyn0916/index.html
这是一个可以开始的地方: http : //www.ibm.com/developerworks/java/library/j-dyn0916/index.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.