开发者

how to change the attribute value using reflection

开发者 https://www.devze.com 2023-01-30 11:35 出处:网络
is it possible to change the value of an attribute of a class using reflection. below is my class :- public class LoggerManager {

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

below is my class :-

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

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

basically i want to change the value of the same to _instance = new NewLogger开发者_如何学GoManager();,

provided that NewLoggerManager extends 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());
  • 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


I have no idea why you need to do this in that way, and basically @Bozho have provided you with correct answer, but I would like to suggest avoiding such traps. You'd better use dependency injection in this case, so it became much more clear and nice and will do the job for you. Try to read about GUICE.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号