views:

88

answers:

4

I'm getting this error when I try to serialize a Method object.

java.io.NotSerializableException: java.lang.reflect.Method

Any Idea?

+3  A: 

java.lang.reflect.Method does not implement java.io.Serializable. So it can not be serialized using the build-in Java methods.

mlk
How do I see which class implement what on the java api.
Marcos Roriz
+3  A: 

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.

lbownik
+1  A: 

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.

Aaron Digulla
That the solution I used to workaround this problem :D
Marcos Roriz
+1  A: 

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;
   }
}
Fedearne