DevShivmohan / Learning-everything

Learning for developer only
0 stars 1 forks source link

Reflection API operations - Java #42

Open DevShivmohan opened 5 months ago

DevShivmohan commented 5 months ago

Using Reflection API to set the private member values

@ToString
class ReflectionA{
    private int a;
}

public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException {
        ReflectionA reflectionA=new ReflectionA();
        ReflectionA reflection=new ReflectionA();
        Field field=reflectionA.getClass().getDeclaredField("a"); // pass the field/variable name
        field.setAccessible(true); // mark as accessible of private member
        field.set(reflection,58); // pass the object in 1st arg and in 2nd arg supply value of that field
        System.out.println(reflectionA);
        System.out.println(reflection);
    }