java - Spring BeanFactory 是如何实例化一个非公共(public)类的?

标签 java spring class-visibility

这里是 Spring 新手。

我观察到 Spring 能够实例化我定义的非公共(public)类(即具有默认可见性的类)。谁能告诉我 Spring 是如何做到这一点的?为什么允许这样做?

最佳答案

好的,这是他们的做法。以这个示例类为例:

package hidden;  

class YouCantInstantiateMe{

    private YouCantInstantiateMe(){
        System.out.println("Damn, you did it!!!");
    }

}

上面是一个包私有(private)的类,在不同的包中有一个私有(private)构造函数,但我们仍然会实例化它:

代码(从不同包中的类运行):

public static void main(final String[] args) throws Exception{
    Class<?> clazz = Class.forName("hidden.YouCantInstantiateMe");
                                            // load class by name
    Constructor<?> defaultConstructor = clazz.getDeclaredConstructor();
    // getDeclaredConstructor(paramTypes) finds constructors with
    // all visibility levels, we supply no param types to get the default
    // constructor
    defaultConstructor.setAccessible(true); // set visibility to public
    defaultConstructor.newInstance();       // instantiate the class
}

输出:

Damn, you did it!!!


当然 Spring 所做的要复杂得多,因为它们还处理构造函数注入(inject)等,但这是实例化不可见类(或不可见构造函数)的方法。

关于java - Spring BeanFactory 是如何实例化一个非公共(public)类的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5430605/

相关文章:

java - 在 Selenium 中自动化时如何禁用 WebDriver 中的 JavaScript?

java - Spring中的JSP页面

java - Spring REST Controller 未映射

spring - 得到错误 : Could not load JDBC driver class [org. postgresql.Driver]

java - 使用私有(private)成员参数化通用类型

module - 如何在 Rust 中相互隐藏兄弟模块?

java - 解决无法将可变参数与varargs结合使用的问题

java - Android aChartEngine 条形图不工作

java - 访问 Shoutcast 当前流信息