I am trying to use reflection to dynamically load Log4j2 libraries and method. The goal being to have my program use Log4j2 if it is found in the class path and to simply log to console if Log4j2 was not found. It works well with the standard log methods, but I can't find how to use the ones with suppliers.
import java.lang.reflect.Array;
import java.lang.reflect.Method;
import java.util.function.Supplier; // This java 8 interface happens to have the same signature as the Log4j2 Supplier interface
public class Test() {
public static void main(String[] args) {
try {
// Starting by loading Log4j2 classes and methods
ClassLoader classLoader = B.class.getClassLoader();
Class<?> classLogManager = classLoader.loadClass("org.apache.logging.log4j.LogManager");
Method methodGetLogger = classLogManager.getMethod("getLogger");
Class<?> interfaceSupplier = classLoader.loadClass("org.apache.logging.log4j.util.Supplier");
Object logger = methodGetLogger.invoke(null);
Method methodFatal = logger.getClass().getMethod("fatal", interfaceSupplier);
// Now trying an ugly trick, but it does not work
Supplier<String> fatalSupplier = new Supplier<String>() {
@Override
public String get() {
System.out.println("fatal log was evaluated");
return "fatal";
}
};
methodFatal.invoke(logger, fatalSupplier);
} catch (Exception e) {
e.printStackTrace();
}
}
}
I get of course the following error:
java.lang.IllegalArgumentException: argument type mismatch
Is there any way to create an object matching the Supplier interface (the Log4j one) without loading statically any Log4j2 class?
Aucun commentaire:
Enregistrer un commentaire