英文:
Add a prefix to base class log messages from a child class
问题
我有一个基类(void)方法,用于记录消息。是否可以从子类方法中为该实例添加前缀?
示例:
假设基类记录 result data
,我可以让它从子类记录 myPrefix: result data
吗?
我正在使用 slf4j。
英文:
I have a base class (void)method which logs a message. Is it possible to add a prefix for that instance from a child class method?
Example:
let say base class logs result data
. Can I make it to log myPrefix: result data
from a child class.
I'm using slf4j
答案1
得分: 1
一个可能的解决方案是使用继承,并使父类抽象,强制子类实现一个返回 `myPrefix` 的方法:
**ParentClass**
```java
public abstract class ParentClass {
public void log(String message) {
logger.log(getLogMessagePrefix() + message);
}
abstract String getLogMessagePrefix();
}
ChildClass
public class ChildClass extends ParentClass {
public final String LOG_PREFIX = "myPrefix";
@Override
String getLogMessagePrefix() {
return LOG_PREFIX;
}
}
<details>
<summary>英文:</summary>
One possible solution is to use inheritance and make the parent class abstract forcing the child class to implement a method that will return `myPrefix`:
**ParentClass**
public abstract class ParentClass {
public void log(String message) {
logger.log(getLogMessagePrefix() + message);
}
abstract String getLogMessagePrefix(); }
**ChildClass**
public class ChildClass extends ParentClass {
public final String LOG_PREFIX = "myPrefix";
@Override
String getLogMessagePrefix() {
return LOG_PREFIX;
}}
</details>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论