简体   繁体   English

SLF4J与继承

[英]SLF4J and inheritance

Say I have: 说我有:

public abstract class Animal {
    // SLF4J
    private Logger logger = LoggerFactory.getLogger(Animal.class);

    // ...etc.

    public void setLogger(Logger logger) {
        this.logger = logger;
    }

    public Logger getLogger() {
        return this.logger;
    }
}

And: 和:

public abstract class Dog extends Animal {
    // SLF4J
    private Logger logger = LoggerFactory.getLogger(Dog.class);

    // ...etc.

    public void setLogger(Logger logger) {
        this.logger = logger;
    }

    public Logger getLogger() {
        return this.logger;
    }
}

Then when I execute the following code: 然后,当我执行以下代码时:

Dog d1 = new Dog();
Animal a1 = new Dog();
  1. Will d1 get a "Dog" logger or an "Animal" logger? d1将获得“狗”记录器还是“动物”记录器?
  2. Will a1 get a "Dog" logger or an "Animal" logger? a1将获得“狗”记录器还是“动物”记录器?
  3. Is there a better/cleaner/safer way to write this code so that Dog and Animal always get the correct logger? 是否有更好/更干净/更安全的方式编写此代码,以便Dog and Animal始终获得正确的记录器?

d1 and a1 will have both types of loggers, ((Animal)d1).logger will be the Animal.class logger and d1.logger will be the Dog.class . d1a1将同时具有两种类型的记录器, ((Animal)d1).logger将是Animal.class记录器,而d1.logger将是Dog.class Note you can't actually reference ((Animal)d1).logger out side of code in Animal class since Animal.logger is a private field. 请注意,由于Animal.logger是一个私有字段,因此您实际上无法在Animal类的代码((Animal)d1).logger引用((Animal)d1).logger

The same will be true of a1 as well since its runtime type is Dog 因为a1的运行时类型是Dog所以也是如此

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

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