mardi 21 avril 2020

Get a private field via reflection, in Java

I have a Java class named "MyClass" with a private attribute, of type "AnotherClass". MyClass has a private constructor, and "AnotherClass" has public constructor. "AnotherClass" has also a private String field, "value", which is initialized in constructor. I want to access in "Main" class this String.

The first class:

public class MyClass {
    private AnotherClass obj;

    private MyClass() {
        obj = new AnotherClass();
    }
}

The second class:

public class AnotherClass {
    private String value;

    public AnotherClass() {
        value = "You got the private value!";
    }
}

The main class:

public class Main {

    static String name;
    static AnotherClass obj;

    public static void main(String[] args) throws Exception {
        Class myClass;
        myClass = Class.forName("main.MyClass");
        Constructor<MyClass>[] constructors = myClass
            .getDeclaredConstructors();
        for (Constructor c : constructors) {
            if (c.getParameters().length == 0) {
                c.setAccessible(true);
                MyClass myCls= (MyClass) c.newInstance();
                Field myObjField = myClass
                    .getDeclaredField("obj");
                myObjField.setAccessible(true);
                obj = (AnotherClass) myObjField.get(myCls);

                // If "value" is public, the program prints "You got the private value!"
                // So "obj" is returned correctly, via reflection
                // name = obj.value; 
                // System.out.println(name); 

                // Now I want to get the field "value" of "obj"
                Field myStringField = obj.getClass().getDeclaredField("value");
                myStringField.setAccessible(true);

                // This line throws an exception
                name = (String) myStringField.get(obj.getClass());

                System.out.println(name); 
            }
        }
    }
}

I expect to see in the console "You got the private value!", but the program throws an exception:

Exception in thread "main" java.lang.IllegalArgumentException: Can not set java.lang.String field main.AnotherClass.value to java.lang.Class

So, I want to retrieve the private field, "value", without modifying "MyClass" and "AnotherClass", and without calling the public constructor from AnotherClass directly in main() . I want to get the value from "obj".





Aucun commentaire:

Enregistrer un commentaire