Preventing class instantiation from other classes

谁都会走 提交于 2019-12-31 02:49:35

问题


I'm working with a domain, view and controllers. Each containing their own classes.

The domain contains a lot of classes that should not be instantiated in classes outside of the domain. I was under the impression the default access modifier was going to help me. Making my domain classes their constructors package visible.

Turns out any class can still use the constructors after importing the right package.class file.

How can I prevent this from happening?


回答1:


When you say 'Turns out any class can still use the constructors after importing the right package.class file.' I guess you are talking about Reflection. Reflection is a powerful concept allowing arbitrary instantiation of classes even if they only provide a private constructor. There is no way to prevent someone from using reflection to instantiate your classes. The class or constructor modifiers such as private or protected can be bypassed using reflection.




回答2:


If you want to control the instantiation of a class from outside of the class then you may create it's constructor private like -

class A{

   private A(){
      // do some thing
   } 

   public static getInstance(){

   }
}   

Now now instance of class A can be created form the outside of the class. But if the outer world realy need an instance of the class then they can use the static method getInstance(). This construction prevents the outer world to create an instance of the class using new keyword.

Hope it will Help.
Thanks.



来源:https://stackoverflow.com/questions/29449374/preventing-class-instantiation-from-other-classes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!