简体   繁体   English

如何使用私有构造函数从final类运行该方法?

[英]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.

相关问题 可以从构造函数调用私有最终方法吗? - Okay To Call Private Final Method from Constructor? Java Final 类或私有构造函数 - Java Final class or private constructor 如何为sonarqube中的最终课程的私有构造函数提供测试覆盖范围? - How to give test coverage for private constructor of a final class in sonarqube? 从最终类(实用程序类)模拟私有静态方法 - Mocking private static method from a final class (utility class) 在最终类中测试私有方法 - Testing a private method in a final class 是否可以在具有私有构造函数的类中访问私有变量并从另一个类更改最终变量值 - Is it possible to access private variable inside a class having private constructor and change final variable value from another class 带有私有构造函数的final类,设计原理是什么 - Final class with private constructor, what is the design principle 它是强制性的实用程序类,应该是最终的私有构造函数吗? - Is it mandatory utility class should be final and private constructor? 如何使用PowerMockito在具有私有构造函数的类中设置原始私有静态final字段? - How do I set a primitive private static final field in a class with private constructor using PowerMockito? 如何从子类构造函数调用超类的私有构造函数? - How to call private constructor of super class from child class constructor?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM