Tutorial How to fix java.io.NotSerializableException: org.apache.log4j.Logger Error in Java
java.io.NotSerializableException: org.apache.log4j.Logger error says that instance of org.apache.lo4j.Logger is not Serializable. This error comes when we use log4j for logging in Java and create Logger in a Serializable class e.g. any domain class or POJO which we want to store in HttpSession or want to serialize it. As we know from 10 Java Serialization interview question that, if you have a non serializable class as member in a Serializable class, it will throw java.io.NotSerializableException Exception.
Look at the below code :
public class Customer implements Serializable{
private Logger logger = Logger.getLogger(Customer.class)
......
}
If instance of Customer will be stored in HttpSession or Serialized externally it will throw "java.io.NotSerializableException: org.apache.log4j.Logger" because here logger instance is neither staticor transientand it doesn't implement Serializable or Externalzable interface.
How to solve java.io.NotSerializableException: org.apache.log4j.Logger
Solving java.io.NotSerializableException: org.apache.log4j.Logger is simple, you have to prevent logger instance from default serializabtion process, either make it transient or static. Making it static final is preferred option due to many reason because if you make it transient than after deserialization logger instance will be null and any logger.debug() call will result in NullPointerException in Java because neither constructornot instance initializer block is called during deserialization. By making it static and final you ensure that its thread-safeand all instance of Customer class can share same logger instance, By the way this error is also one of the reason Why Logger should be declared static and finalin Java program. Just make following code change to fix java.io.NotSerializableException: org.apache.log4j.Logger in Java.
public class Customer implements Serializable{
private static final Logger logger = Logger.getLogger(Customer.class)
......
}
That's all on how to fix java.io.NotSerializableException: org.apache.log4j.Logger in Java. We have seen what cause java.io.NotSerializableException: org.apache.log4j.Logger, it's because Logger class is not Serializable but we also learned that there is no point serializing Logger instance and better to make Logger static and final.
Comments
Post a Comment
-Berkomentarlah yang baik dan rapi.
-Menggunakan link aktif akan dihapus.