java - 是否可以访问具有私有构造函数的类中的私有变量并从另一个类更改最终变量值
问题描述
如何访问具有私有构造函数的类中的私有变量。如果变量是从另一个类声明为 final 的,我该如何更改它的值。尝试了一些链接但无法获得,因为大多数解决方案都具有公共构造函数,例如:
我试过的代码:
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
变量,你应该考虑不要把这个变量作为最终变量。
推荐阅读
- laravel - 如何在 Raspberry Pi 上托管 Laravel 项目
- python - 上传amazon s3 python,boto3后获取文件url
- ibm-cloud - IBM Cloud App ID:忘记密码和重新认证流程
- spring - Spring Boot 和 Spring Cloud 上的服务发现错误
- c# - 在 ASP.net 中创建类似 cURL 的请求
- python - 在 for 循环中不转换到下一个
- vue.js - 导入 nuxtjs 中模块化的 UI 库
- ios - ios:UIPageControl 的垂直位置不明确
- c# - C# Linq 从 ToDictionary 获得不正确的结果
- grails - Grails 3 - 域中的几何类型