Yt100
Yt100

Reputation: 334

how to prevent invoke private constructor through reflect in Java

I have a java class named Test which has a single, private constructor because I require it to be a singleton, like this:

class Test {
    private static final Test INSTANCE = new Test();
    private Test() { }
    public static Test getInstance() { return INSTANCE; }

    // other code
}

How to prevent others from instantiating Test through reflection in Java?

Upvotes: 1

Views: 299

Answers (2)

Shubham
Shubham

Reputation: 549

You can use enum as they are internally created, initialized by JVM. Invocation of enum is also done internally, so they cannot be accessed by reflection as well

public enum Test
{ 
  INSTANCE; 

//other methods etc

} 

PS: drawback is you won't be able to lazy initialize it. However some threads have suggested that they can be lazy intialized https://stackoverflow.com/a/15470565/4148175 , https://stackoverflow.com/a/16771449/4148175

Upvotes: 3

Vikas
Vikas

Reputation: 7165

You can throw exception in private contructor if object is already created,

private Test() {
    if (INSTANCE != null)
        throw new IllegalArgumentException("Instance already created");
}

Upvotes: 3

Related Questions