我在一个类中看到了以下内容:
this.logger.severe("");
this.logger.warning("");
this.logger.info("");
有几件事我不明白:
我们如何使用之前未定义的方法?我的意思是,类中没有定义“记录器”方法。我认为可以定义这些方法,因为所考虑的类是定义了“记录器”的另一个类的扩展。但是在类的定义中没有“extends”语句(只有“implements”)。
我能理解这样的事情:“objectName.methodName”。但是“objectName.something1.something2”是什么? “something1.something2”是方法的名称?方法名可以带点吗?
这些“logger.*”究竟是做什么的?我认为他们保存了有关代码执行的信息。他们有点写关于执行过程中发生的事情的报告。但是我在哪里可以找到这些信息?
已添加:
在文件的开头我有:import java.util.logging.Logger;
然后在类里面我有:private Logger logger = Logger.getLogger("a.b.c.d")
;
因此,logger 是 Logger 类的一个对象(但我不明白为什么他们不能使用“new Logger()”以通常的方式实例化该类)。我也不明白 logger.severe("") 究竟做了什么.
最佳答案
记录器没有做任何特别的事情。全部只是 Java 代码。
public class SomeClass {
private Logger logger = LogFactory.getLogger(SomeClass.class);
public void doSomething() {
this.logger.debug("foo");
}
}
this.logger
只是指向当前实例(this
)的名为logger
的实例变量。 this.
前缀在此示例中是多余的。也可以在此处执行 logger.debug("foo")
。
如果它没有在 SomeClass
本身中声明,那么它很可能是在扩展类中声明的。检查在 extends
中声明的类。
关于您的 objectName.something1.something2
疑问,您是否已经了解了 System.out.println()
的工作原理? System.out
返回一个 PrintStream
对象,该对象又具有 println()
方法。因此,如果 objectName.something
返回一个完整的带有方法的 Object
,那么您可以继续链接方法调用。
基本上,
objectName.something1.something2;
可以翻译成
SomeObject someObject = objectName.something1;
someObject.something2;
但是,如果您在代码中的其他任何地方都不需要 someObject
,则可以像您的示例一样缩短它。
更新:根据您的更新:
So, logger is an object of the class Logger (but I do not understand why they could not instantiate the class in a usual way using "new Logger()). I also do not understand what exactly logger.severe("") do.
Just read the javadoc of the class in question what it all does .至于为什么不能实例化,是因为factory pattern .
更新 2:根据另一个困惑:
I do not understand why they use "this". I mean, if I use just field name, will it not be, by default, the field of this object? I there any difference between "this.x" and "x"?
这样您就可以更明确地知道您想要访问哪一个。例如,如果该方法包含名称为 logger
的参数或局部变量,则 this.logger
仍会引用实例变量。
public class SomeClass {
private Logger logger = LogFactory.getLogger(SomeClass.class);
public void doSomething(Logger logger) {
this.logger.debug("foo"); // Refers to the instance variable.
logger.debug("foo"); // Refers to the method argument.
}
public void doSomethingElse() {
Logger logger = LogFactory.getLogger(SomeClass.class);
this.logger.debug("foo"); // Refers to the instance variable.
logger.debug("foo"); // Refers to the method local variable.
}
}
关于java - Java 中的 "logger"是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2411022/