是否可以在具有私有构造函数的类中访问私有变量,并从另一个类

时间:2018-06-15 07:36:39

标签: java

如何在具有私有构造函数的类中访问私有变量。   如果变量从另一个变量声明为final,我该如何更改它的值   class.Have尝试了几个链接,但无法获得,因为大多数解决方案都有公共构造函数,如:

Link 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 个答案:

答案 0 :(得分:0)

如果要更改checkValue1变量,则应考虑不将此变量作为最终变量。