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:
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();
}
}
}