title: Singleton: How to stop create instance via Reflection
body: <p>I know in Java we can create an instance of a Class by <code>new</code>, <code>clone()</code>, <code>Reflection</code> and by <code>serializing and de-serializing</code>.</p>
  
  <p>I have create a simple class implementing a Singleton.</p>
  
  <p>And I need stop all the way one can create instance of my Class.</p>
  
  <pre><code>public class Singleton implements Serializable{
      private static final long serialVersionUID = 3119105548371608200L;
      private static final Singleton singleton = new Singleton();
      private Singleton() { }
      public static Singleton getInstance(){
          return singleton;
      }
      @Override
      protected Object clone() throws CloneNotSupportedException {
          throw new CloneNotSupportedException("Cloning of this class is not allowed"); 
      }
      protected Object readResolve() {
          return singleton;
      }
      //-----&gt; This is my implementation to stop it but Its not working. :(
      public Object newInstance() throws InstantiationException {
          throw new InstantiationError( "Creating of this object is not allowed." );
      }
  }
  </code></pre>
  
  <p>In this Class I have managed to stop the class instance by <code>new</code>, <code>clone()</code> and <code>serialization</code>, But am unable to stop it by Reflection.</p>
  
  <p>My Code for creating the object is</p>
  
  <pre><code>try {
      Class&lt;Singleton&gt; singletonClass = (Class&lt;Singleton&gt;) Class.forName("test.singleton.Singleton");
      Singleton singletonReflection = singletonClass.newInstance();
  } catch (ClassNotFoundException e) {
      e.printStackTrace();
  } catch (InstantiationException e) {
      e.printStackTrace();
  } catch (IllegalAccessException e) {
      e.printStackTrace();
  }
  </code></pre>