views:

213

answers:

3

If not, maybe you could tell me why.

I get NotSerializableException when my class is being serialized.

Inside the class I am passing this anonymous class to a method:

new org.apache.commons.collections.Closure() {
   ...
};

The question is still unanswered. I want to know if there is a standard Closure interface that implements Serializable

+2  A: 

All references in your class must be of the type Serializable as well, even the Closure type. Is it an interface? It must extend the java.io.Serializable interface.

I.e:

interface Closure extends java.io.Serializable {
    ...
}

class YourClass implements java.io.Serializable {
    private Closure closure;
    ...
    public void setClosure(Closure closure) {
        this.closure = closure;
    }
}
...
    private static void main(String[] args) {
        YourClass y = new YourClass();
        y.setClosure(new Closure() {
            ...
        });
        ...

Edit, clarifications. :)

Björn
There is no need for base classes to be serialisable (although the most derived non-serialisable class must have a no-args constructor accessible by the base-most serialisable class.
Tom Hawtin - tackline
I am using apache's Closure interface. I wonder why it doesn't implement Serializable.
HappyCoder
+2  A: 

Your main trouble here is that nested classes do not have standardised serial form. Note also that if you are in an instance method, the outer class objects will also be serialised (through a field with an unspecified name).

If you don't care if your code stops working at an entirely random point, you might want to consider a plain local class instead (or in addition to) and anonymous inner class.

Tom Hawtin - tackline
You are right. "Findbugs" is warning me too:Pattern id: SE_INNER_CLASS, type: Se, category: BAD_PRACTICEThis Serializable class is an inner class. Any attempt to serialize it will also serialize the associated outer instance [...]
HappyCoder
Yay for Findbugs.
Tom Hawtin - tackline
A: 

Is there a standard closure interface that is Serializable?

I guess not.

HappyCoder