3

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

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

Any Idea?

Marcos Roriz Junior
  • 4,076
  • 11
  • 51
  • 76

4 Answers4

7

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.

Łukasz Bownik
  • 6,149
  • 12
  • 42
  • 60
3

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

Michael Lloyd Lee mlk
  • 14,561
  • 3
  • 44
  • 81
  • 1
    How do I see which class implement what on the java api. – Marcos Roriz Junior Nov 20 '09 at 11:36
  • 1
    @MarcosRorizJunior In the Javadoc to which mlk linked, there's a section that says, e.g. (for Method), "**All Implemented Interfaces:** AnnotatedElement, GenericDeclaration, Member". Those are the interfaces that the class implements. – Joshua Taylor Nov 05 '13 at 02:21
3

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
  • 321,842
  • 108
  • 597
  • 820
1

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
  • 7,049
  • 4
  • 27
  • 31