jeudi 15 mars 2018

Java reflection does not work as expected

I just wrote this code to test something for a better understanding of reflection.

This is the ReflectionTestMain class:

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class ReflectionTestMain {
    public static void main(String[] args) {
        try {
            ReflectionTest rt = new ReflectionTest();
            Class<ReflectionTest> c = ReflectionTest.class;
            Field f = c.getDeclaredField("value");
            f.setAccessible(true);
            f.set(rt, "text");
            Method m = c.getDeclaredMethod("getValue");
            m.setAccessible(true);
            String value = (String) m.invoke(rt);
            System.out.println(value);
        } catch (NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException | NoSuchMethodException | InvocationTargetException e) {
            e.printStackTrace();
        }
    }
}

And this is the ReflectionTest class.

public class ReflectionTest {
    private final String value = "test";

    private String getValue() {
        return value;
    }
}

This code prints test but I expected it prints text. What is the reason that this does not work and how can I fix that?





Aucun commentaire:

Enregistrer un commentaire