mercredi 15 juin 2022

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

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





Aucun commentaire:

Enregistrer un commentaire