Singleton: How to stop create instance via Reflection

how to prevent singleton pattern from reflection serialization and cloning in java
how to prevent singleton pattern from reflection serialization and cloning in c#
how to prevent singleton class from cloning
how to avoid singleton
how to break singleton pattern in java using reflection
how do you prevent singleton pattern from reflection cloning and serialization
singleton class in java
singleton using enum

I know in Java we can create an instance of a Class by new, clone(), Reflection and by serializing and de-serializing.

I have create a simple class implementing a Singleton.

And I need stop all the way one can create instance of my Class.

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;
    }
    //-----> 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." );
    }
}

In this Class I have managed to stop the class instance by new, clone() and serialization, But am unable to stop it by Reflection.

My Code for creating the object is

try {
    Class<Singleton> singletonClass = (Class<Singleton>) Class.forName("test.singleton.Singleton");
    Singleton singletonReflection = singletonClass.newInstance();
} catch (ClassNotFoundException e) {
    e.printStackTrace();
} catch (InstantiationException e) {
    e.printStackTrace();
} catch (IllegalAccessException e) {
    e.printStackTrace();
}

Try creating your public constructor

private Singleton() {
    if( Singleton.singleton != null ) {
        throw new InstantiationError( "Creating of this object is not allowed." );
    }
}

Singleton: How to stop create instance via Reflection, Overcome reflection issue: To overcome issue raised by reflection, enums are that object it will create a new instance and hence break the singleton pattern. I know in Java we can create an instance of a Class by new, clone(), Reflection and by serializing and de-serializing. I have create a simple class implementing a Singleton. And I need stop all t

Define the singleton like this:

public enum Singleton {
    INSTANCE
}

How to prevent Singleton Pattern from Reflection, Serialization and , For this purpose, we make the constructor of the class a private and return a instance via a static method. But using reflection, we can still create  A Singleton pattern states that a class can have a single instance and multiple instances are not permitted to be created. For this purpose, we make the constructor of the class a private and return a instance via a static method. But using reflection, we can still create multiple instance of a class by modifying the constructor scope.

How about checking in the constructor:

private Singleton() {
    if (singleton != null) {
        throw new IllegalStateException("Singleton already constructed");
    }
}

Of course, this may not really stop it - if someone is messing around with reflection to access private members, they may be able to set the field to null themselves. You have to ask yourself just what you're trying to prevent though, and how worthwhile it is.

(EDIT: As Bozho mentioned, final fields may not be settable even via reflection. I wouldn't be surprised if there were some way of doing it via JNI etc though... if you give folks enough access, they'll be able to do almost anything...)

How to prevent Reflection to break a Singleton Class Pattern?, Create one instance using private constructor and store it in private static variable​. Provide How to prevent Reflection API from breaking Singleton However, we can not use this technique with lazy initialization approach. Hence, reflection can’t break singleton property in case of enums. Serialization:- Serialization can also cause breakage of singleton property of singleton classes. Serialization is used to convert an object of byte stream and save in a file or send over a network. Suppose you serialize an object of a singleton class.

private Singleton() { 
    if (Singleton.singleton != null) {
        throw new RuntimeException("Can't instantiate singleton twice");
    }
}

Another thing you should watch is the readResolve(..) method, because your class implements Serialiable. There you should return the existing instance.

But the easiest way to use singletons is through enums - you don't worry about these things.

Breaking Singleton using reflection and Enum Singleton, Now create class name Test to test that above implementation. In the following Test class, I have created two instances of Singleton class by using getInstance()​  Singleton Pattern from Reflection, Serialization and Cloning,java - Singleton: How to stop create instance via Reflection,java Singleton - prevent multiple creation through reflection,java - How to deal with Singleton along with Serialization ,Reflection Proofing the Java Singleton Pattern when using Lazy ,Java Singleton Design Pattern Example Best Practices

As an alternative to the singleton, you could take a look at the monostate pattern. Then, instantiation of your class is not a problem anymore, and you don't have to worry about any of the scenarios you listed.

In the monostate pattern, all the fields in your class are static. That means that all instances of the class share the same state, just like with a singleton. Moreover, this fact is transparent to the callers; they don't need to know about special methods like getInstance, they simply create instances and work with them.

But, just like with singleton, it's a form of hidden global state; which is very bad.

How to prevent Singleton Pattern from Reflection and Cloning, In Java, singleton pattern is used to avoid creation of multiple instances of a how to create singleton class rather than we focus on those concepts by which this  There are many ways to prevent Singleton pattern from Reflection API, but one of the best solutions is to throw a run-time exception in the constructor if the instance already exists. In this, we

How To Save Singleton Pattern from Reflection Serialization and , There are available techniques to prevent such reflection attacks. One of an exception in the constructor if it's asked to create a second instance. Source) at TestSingleton.main(TestSingleton.java:13) Caused by: java.lang. Policy File Changes and Invocation. Creating a policy file. Start the policy tool present in your JDK bin folder, and click “Add Policy Entry”. Enter the path to your Singleton class in the code base, the format of a URL. Do not include the package folder, and make sure your client classes reside in a different folder.

Reflection Proofing the Java Singleton Pattern when using Lazy , The singleton allows only one entry point to create the new instance of the class. In above Singleton class, by using reflection you can create more than one instance. To prevent Singleton failure while due to reflection you have to throw a  Steps to create singleton class in Java: Create INSTANCE of same class by instantiating class & this INSTANCE should be with private & static modifier; Provide public static method that returns same INSTANCE of class every time; Finally, create private constructor so that no-one create object from outside of class

How to make the perfect Singleton? - Keval Patel, In this post, we will discuss how it can break and how to prevent those. package demo1; public final class Singleton { private static volatile Singleton instance Using Reflection API we can create multiple objects in singleton class. Example to show how reflection can break the singleton pattern with  For all those who are anxious to know how this could be done to break a Singleton class or how to write Singleton class so that it is not broken, there is some interesting stuff below: 1. Break by Cloning. If a Singleton class implements java.lang.Cloneable interface then invoking clone() method on its single instance creates a duplicate object. Consider the below code:

Comments
  • You have accepted the wrong answer - the right one is stackoverflow.com/a/6994437/281545
  • All answers are not solving this problem.
  • I know that my question is somehow out of scope but can you tell me how did you managed to stop creating a class instance via reflexion ? I couldn't see such a thing in your code
  • Wow ... great minds think alike ... 3 answers almost identical ... hysterical.
  • Now problem for me, Which Answer to Accept :)
  • I'd say this one because the excepception thrown is the most appropriate (InstanciationError).
  • I just used what was technically the body of newInstance(). I think, although not sure, the newInstance() method can be removed as that is actually a java.lang.Class<?> method and the method implementation provided in the question initially would do nothing.
  • There is a flaw in this approach, by which what if we create the instance using reflection before any getInstance invocation(with lazy init)? Reflection is still allowed to proceed as the static variable is still null at that time.
  • Enum is a sure shot gaurantee against Reflection,clone and serialization-deserialization
  • But ENUM has it's restriction. I am actually looking for a solution which is apart from ENUM
  • @Diganta what restrictions?
  • Enum is the cleanest way of providing singleton behavior in Java, bar none. As Kumar Abhinav stated, it provides these guarantees in the simplest, least error prone way.