1
votes

How can I access private variable inside a class having private constructor. And how can I change it's value if the variable is declared final from another class.Have tried few links but not able to get as most of the solutions are having public constructor like:

Link i have tried

Code I have tried:

  package com.test.app;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;

public class Demo {

    static Demo instance = null;
    private int checkvalue = 10;
    final private int checkvalue1 = 12;

    private Demo() {
        System.out.println("Inside Private Constructor");
        System.out.println(checkvalue);
    }

    static public Demo getInstance() {
        if (instance == null)
            instance = new Demo();

        return instance;
    }

}

class Main {

    public static void main(String args[]) {
        try {
            ///this is showing me the value inside the constructor
            Class clas = Class.forName("com.test.app.Demo");
            Constructor<?> con = clas.getDeclaredConstructor();
            con.setAccessible(true);
            con.newInstance(null);


            ///how can i get the value of the private variables inside the class
            Field f = Demo.class.getDeclaredField("checkvalue");
            f.setAccessible(true);
            ////throwing me a error 
            //java.lang.IllegalArgumentException: Can not set int field com.test.app.Demo.checkvalue to java.lang.reflect.Constructor
            System.out.println("" + f.get(con));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
1
Can't change final variables. That is what the keyword is for - XtremeBaumer
May I ask why you want to do this? I can't imagine a use-case where this is actually useful. - Ben
yes actually i was asked in an interview.they told me this is possible using java reflection. - avik
Ah okay, that does make sense although I personally would consider it a horrible interview question. I don't think you can achieve this with "simple reflection" and need to go a step further to bytecode manipulation. PowerMockito is a library capable of doing what you want to achieve. This question should be a good reference point. - Ben
ok let me give a try :) - avik

1 Answers

0
votes

if you would to change checkValue1 variable, you should to considere to not put this variable as final.