简体   繁体   English

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

[英]Is it possible to access private variable inside a class having private constructor and change final variable value from another class

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: 如果变量是从另一个类声明为final的,该如何更改其值呢?尝试了很少的链接,但由于大多数解决方案都具有以下公共构造函数而无法获取:

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM