如何访问类的私有构造函数? [英] How can I access a private constructor of a class?

查看:165
本文介绍了如何访问类的私有构造函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是一名Java开发人员。在一次采访中,我被问到私人构造函数的问题:


你能访问一个类的私有构造函数并实例化它吗? >

我回答不,但是错了。



解决方案


  • 您可以访问它

  • 如果是嵌套类,则可以从封闭类中访问它



  • 这不是真的清楚,如果这些都适用 - 你能提供更多的信息吗?


    I am a Java developer. In an interview I was asked a question about private constructors:

    Can you access a private constructor of a class and instantiate it?

    I answered 'No' but was wrong.

    Can you explain why I was wrong and give an example of instantiating an object with a private constructor?

    解决方案

    • You can access it within the class itself (e.g. in a public static factory method)
    • If it's a nested class, you can access it from the enclosing class
    • Subject to appropriate permissions, you can access it with reflection

    It's not really clear if any of these apply though - can you give more information?

    这篇关于如何访问类的私有构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆