Reflection returns two constructors when accessing a private constructor from the inner class

public class Base {

    private Base instance;

    private Base() {
    }

    public static class BaseHelper {
        Base instance = new Base();
    }
}

In the above example, I have one constructor with no arguments in the base class. Now I list the constructors of this class as follows:

Constructor<?>[] constructors = Base.class.getDeclaredConstructors();
System.out.println(constructors);

When I run this code, I get the following output:

[private com.Base(), com.Base(com.Base)]

This tells me that there are two constructors:

  • private constructor that I declared
  • public default constructor

Why is this?

+4
source share
1 answer

The compiler creates two constructors because your class BaseHelperaccesses the private constructor of your class Base.

"" . BaseHelper Base, - . , .

Synthetic - .

package de.test;

import java.lang.reflect.Constructor;

public class Base {

    private Base instance;

    private Base() {
    }

    public static class BaseHelper {
        Base instance = new Base();
    }

    public static void main(String[] args) {
        Constructor[] constructors = Base.class.getDeclaredConstructors();
        for (Constructor constructor : constructors) {
            System.out.println(constructor + " - synthetic? " + constructor.isSynthetic());
        }
    }
}
+8

Source: https://habr.com/ru/post/1570265/


All Articles