how to change the attribute value using reflection
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
Fielddefinition for the_instancefield. 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
nullas target object, because the field isstatic
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.
加载中,请稍侯......
精彩评论