How to make the Inner Class non-instantaneous?

I need a static inner class that cannot be created even by an outer class. Right now I have documentation that says: "Please do not create an instance of this object." Can I give a better signal?

+1
source share
3 answers

I need a static inner class that cannot be created even by an outer class.

I guess that “outer class” really means an encompassing class.

  • If you do not want to limit the enclosing class, then creating a single constructor for the private class will have the desired effect.

  • If you also want to limit the scope of the class, the answer is that there is no way to do this. If you declare the constructor of inner classes 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 this class.

However, I would suggest that this (i.e. preventing the entire instance of the inner class) is a meaningless exercise. Any non-static declarations in the inner class cannot be used in any way, and any static declarations can also be declared in the enclosing class.

In addition, everything you do to “prevent” the surrounding class from being an instance of the inner class can be circumvented by editing the source file containing two classes. And even a class with a private constructor can be created using reflection if you do it right.

+8
source

Restore it and make it an anonymous class.

0
source

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, which is just

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

Thus, no classes except the outer class can “see” the constructor, and the outer class cannot use the constructor without having to try / catch or throw for Do_Not_Instantiate_This_Class to even compile, and it will always catch or throw it during fulfillment. Not entirely optimal, but I think this is done the way you want.

0
source

Source: https://habr.com/ru/post/1308581/


All Articles