开发者

How do I make the Inner Class uninstantiable?

开发者 https://www.devze.com 2022-12-29 01:35 出处:网络
I want a static inner class that can\'t be instantiated even by the external class. Right now I just have a do开发者_StackOverflowcumentation that says \"Please don\'t instantiate this object\". Can I

I want a static inner class that can't be instantiated even by the external class. Right now I just have a do开发者_StackOverflowcumentation that says "Please don't instantiate this object". Can I give a better signal?


I want a static inner class that can't be instantiated even by the external class.

I assume that "external class" really means the enclosing class.

  • If you don't want to restrict the enclosing class, then making the only constructor of the inner class private will have the desired effect.

  • If you also want to restrict the enclosing class, the answer is there is no way to do this. If you declare the inner classes constructor as private, the enclosing class can still access it and instantiate it. If you declare the inner class as abstract, the enclosing class can still declare a subclass and instantiate that class.

However, I would suggest that this (i.e. preventing all instantiation of an inner class) is a pointless exercise. Any non-static declarations in the inner class could not be used in any way, and any static declarations may as well be declared in the enclosing class.

Besides, anything that you do to "prevent" the enclosing class from instantiating the inner class can be circumvented by editing the source file containing the two classes. And even a class with a private constructor can be instantiated using reflection, if you go about it the right way.


Restructure it and make it an anonymous class.


First create the following in a separate file:

public Do_Not_Instantiate_This_Class extends Exception {
    /*
    *Please Do Not Instantiate This Class
    */
    private static final long serialVersionUID = 1L;
}

Then, make a constructor in your inner class that is just

private final innerClass() throws Do_Not_Instantiate_This_Class {
    throw(new Do_Not_Instantiate_This_Class());
}

That way, no classes other than the external class can "see" the constructor, and the external class cannot use the constructor without having a try/catch or throws declaration of Do_Not_Instantiate_This_Class in order to even compile, and it will always catch or throw it in runtime. Not totally optimal, but I think it gets done what you want it to.

0

精彩评论

暂无评论...
验证码 换一张
取 消