1

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();
        }
    }
}
avik
  • 117
  • 9
  • 3
    Can't change `final` variables. That is what the keyword is for – XtremeBaumer Jun 15 '18 at 07:38
  • 3
    May I ask why you want to do this? I can't imagine a use-case where this is actually useful. – Ben Jun 15 '18 at 07:38
  • yes actually i was asked in an interview.they told me this is possible using java reflection. – avik Jun 15 '18 at 07:40
  • 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](https://stackoverflow.com/questions/23162520/powermock-mock-out-private-static-final-variable-a-concrete-example) should be a good reference point. – Ben Jun 15 '18 at 07:42
  • ok let me give a try :) – avik Jun 15 '18 at 07:48
  • Your code has a bug. You need to save the instance you create: Object instance = con.newInstance(null). Then you should pass the instance to the field: f.get(instance). As it is you pass the constructor and that is the wrong type. After that your example may well work. – ewramner Jun 15 '18 at 07:51

1 Answers1

0

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

s4r4z1n
  • 7
  • 3