Why is it impossible to construct private objects through reflection in Java

56 Views Asked by At

I clearly set the constructor's setAccessible to true, but why is it still an error! can you tell me how to fix it

public class Person {
    // fields...

    private Person(String name, int age, String address, int num) {
        this.name = name;
        this.age = age;
        this.address = address;
        this.num = num;
        System.out.println("private full-constructor be created");
    }

}

// error happend ?! why?

public static void operatePrivateConstructorFullParameter(Class<? extends Person> clzz) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
    Constructor<? extends Person> constructor = clzz.getConstructor(String.class, int.class, String.class, int.class);
    constructor.setAccessible(true);

    Person person = constructor.newInstance("Miao", 18, "MOON", 88);
}


public static void main(String[] args) throws Exception {
    Class<? extends Person> clzz = Person.class;
    operatePrivateConstructorFullParameter(clzz);
}

enter image description here

2

There are 2 best solutions below

0
On

Try this

Constructor<Person> constructor= (Constructor<Person>) Person.class.getDeclaredConstructors()[0];
1
On

This error isn't about accessibility, it's about finding the constructor.

As specified in its documented contract, the method Class.getConstructor() will only find public constructors.

If you want to find this private constructor, you need to use getDeclaredConstructor() with the correct parameter types

Once you find the constructor, you will still need to make it accessible. Be aware, however, that in a modular application, encapsulation can prevent you from using reflection this way.