项目中遇到了一个异常:
java.lang.IncompatibleClassChangeError: Class org.apache.logging.slf4j.Log4jLogger does not implement the requested interface org.slf4j.Logger
看了下Log4jLogger的声明:
public class Log4jLogger implements LocationAwareLogger, Serializable {
public interface LocationAwareLogger extends Logger {
package org.slf4j;
public interface Logger {
org.apache.logging.slf4j.Log4jLogger明明是org.slf4j.Logger的子类?这个问题一般是由于类加载器不一样导致的。的确,项目中用到了URLClassLoader加载使用其他jar。
解决办法,org.slf4j.Logger
这个类全部使用application classloader加载,即在loadClass方法中过滤掉org.slf4j.Logger
,不用URLClassLoader加载该类。
@Override
protected Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException {
Class cl;
if (name.equals("org.slf4j.Logger")) {
cl = this.getClass().getClassLoader().loadClass(name);
} else {
try {
cl = super.loadClass(name, resolve);
} catch (ClassNotFoundException ex) {
cl = this.getClass().getClassLoader().loadClass(name);
}
}
return cl;
}