I'm getting this error when I try to serialize a Method object.
java.io.NotSerializableException: java.lang.reflect.Method
Any Idea?
I'm getting this error when I try to serialize a Method object.
java.io.NotSerializableException: java.lang.reflect.Method
Any Idea?
java.lang.reflect.Method
does not implement java.io.Serializable
. So it can not be serialized using the build-in Java methods.
You can do it manually. Just serialize your class name, method name and parameter class names as strings and then recreate your Method object using a reflection mechanism during deserialization.
Class.forName(clsName).getMethod("methodName", Class.forName(param1ClsName), ....);
If you implement Externalizable interface then You can use your class as regular serializable class.
There is no way to serialize a method object in a portable way since it doesn't contain all the necessary information to restore it (for example, the bytecode).
Instead, you should serialize the name of the class, the method name and the parameter types. Then you can recreate the Method
instance during deserialization.
Assuming that the java.lang.reflect.Method
object is a member of another class, you should mark it as transient, and recreate it using class name and method name/signature after deserialization.
You could implement an MethodInfo class for this purpose.
class SerializableClass {
private transient Method m_method; //Not serialized
private MethodInfo m_methodInfo;
public Method getMethod() {
if(m_method != null) {
//Initailize m_method, based on m_methodInfo
}
return m_method;
}
}