1

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?

Abra
  • 19,142
  • 7
  • 29
  • 41
Yt100
  • 324
  • 4
  • 12
  • Did you try searching the Internet for the words ___java singleton prevent reflection___ ? – Abra Jul 08 '20 at 06:21

2 Answers2

3

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

private Test() {
    if (INSTANCE != null)
        throw new IllegalArgumentException("Instance already created");
}
Vikas
  • 6,868
  • 4
  • 27
  • 41
3

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

Shubham
  • 549
  • 4
  • 11