lundi 11 avril 2022

How to make sure instance of a class with a private constructor can not be created from outside of the class using Reflection?

I know that an instance of a class with a private constructor can be created using reflection but is there any way to make sure that the instance of the class can only be created within the same class using its own private constructor?

Let's take an example of a class Test, with a private constructor.

import java.lang.reflect.Constructor;

   import java.lang.reflect.InvocationTargetException;

   class Test   
   {

      private Test()  //private constructor
      {
      } 
   }

  public class Sample{

      public static void main(String args[]) throws ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchMethodException, SecurityException, IllegalArgumentException, InvocationTargetException
     {

       Class c=Class.forName("Test"); //specify class name in quotes

       //----Accessing private constructor
       Constructor con=c.getDeclaredConstructor();
       con.setAccessible(true);     
       Object obj=con.newInstance();
   }   
} 

My question is - is there any way to ensure that the instance of the class can only be created within the same class and not from outside using reflection or any other method?





Aucun commentaire:

Enregistrer un commentaire