我有一个演员问题,其生成java.lang.ClassCastException
例外:
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.core.LoggerContext;
import org.apache.logging.log4j.message.MessageFactory;
public class MyLogger extends org.apache.logging.log4j.core.Logger {
MyLogger(LoggerContext context, String name, MessageFactory messageFactory) {
super(context, name, messageFactory);
// TODO Auto-generated constructor stub
}
public static MyLogger getLogger(String name) {
org.apache.logging.log4j.core.Logger logger_ = (org.apache.logging.log4j.core.Logger) LogManager
.getLogger(name);
return (MyLogger) logger_;
}
}
虽然这与此原理相同:
public class test {
private static class A {
}
private static class B extends A {
}
public static void main(String [] args) {
A a = new A();
B b = new B();
a = (A) b;
}
}
有人可以解释一下吗?
答案 0 :(得分:1)
LogManager.getlogger(name)
返回org.apache.logging.log4j
个对象(界面)
您正试图将此对象存储在org.apache.logging.log4j.core.Logger
对象(实现)中,但它无法正常工作。这是一个例子:
您可以在对象中存储字符串:
String s = "foo";
Object o = s;
但是你不能在String中存储一个Object:
Object o = new Object();
String s = o; // Won't compile
此处,对象为org.apache.logging.log4j
,字符串为org.apache.logging.log4j.core.Logger
这是一个解决方案:
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.core.LoggerContext;
import org.apache.logging.log4j.message.MessageFactory;
public class MyLogger extends org.apache.logging.log4j.core.Logger
{
MyLogger(LoggerContext context, String name, MessageFactory messageFactory) {
super(context, name, messageFactory);
}
public static Logger getLogger(String name) {
Logger logger_ = LogManager.getLogger(name);
return logger_;
}
}
答案 1 :(得分:0)
请用英文! (En anglais svp!)
在您的代码中:
MyLogger extends Logger
表示您可以将MyLogger转换为Logger,但是您无法将Logger强制转换为MyLogger。
例如,如果Dog extends Animal - >你可以说狗是动物,但你不能说动物总是狗!