如何使用反射改变属性值 [英] how to change the attribute value using reflection

查看:50
本文介绍了如何使用反射改变属性值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以使用反射来更改类的属性值.

is it possible to change the value of an attribute of a class using reflection.

下面是我的班级:-

public class LoggerManager {

    private static LoggerManager _instance = new LoggerManager();

    private LoggerManager() {
    }

    public static LoggerManager getInstance() {
            return _instance; 
    }

    public Logger getLogger(String FQCN) {
        Logger logger =  Logger.getLogger(FQCN);
        logger.setLevel(Level.INFO);
        return logger;
    }
}

我想使用反射改变 _instance 变量的值..

i want to change the value of _instance variable using reflection..

基本上我想将相同的值更改为 _instance = new NewLoggerManager();,

basically i want to change the value of the same to _instance = new NewLoggerManager();,

前提是 NewLoggerManager 扩展 LoggerManager

是否可以这样做,因为我知道如何调用方法,但是如何执行此操作.. ???

is it possible to do so, as i know how to invoke methods, but how to do this one.. ???

推荐答案

Field field = LoggerManager.class.getDeclaredField("_instance");
field.setAccessible(true);
field.set(null, new NewLoggerManager());

  • 第一行获取_instance 字段的Field 定义.使用declared"方法,因为它也可以获取私有字段
  • 设置该字段可用于反射操作,即使由于其可见性而无法实现.
  • 设置一个新对象.传递 null 作为目标对象,因为该字段是 static
    • the first line obtains the Field definition for the _instance field. Using the "declared" method, because it is able to obtain private fields as well
    • setting the field to be accessible for reflective operations even if this would not be possible due to its visibility.
    • setting a new object. Passing null as target object, because the field is static
    • 这篇关于如何使用反射改变属性值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆