Mohitt
Mohitt

Reputation: 2977

Java: Take anonymous class outside

I have a situation presented below:

Class C1 {

    public static void main(String[] args) {
        Object o = // new object of some class
        delegate(new C2() {             // C2 is an abstract class or interface
            public void delegateLogic() {
                Object my_o = o;  // refrences main's local variable
                // huge method body
                // object o local to main is required here  
            }
        });
    }

    private void delegate(C2 c2) {
        // method body
    }
}

The body of delegateLogic() is turning out to be very big. For code maintainability :

  1. I want to create a concrete class from C2 and keep it outside, while still having a way to use object o in the main method.
  2. Also, instance of C2 are supposed to be serializable and unfortunately object o is not serializable. So, I do not want to create a member object in C2 by passing object o in the constructor.

Any ideas?

Upvotes: 1

Views: 133

Answers (2)

sprinter
sprinter

Reputation: 27976

If C2 becomes an external class then it must have the reference to o passed to it in some form to use it in delegateLogic. You really only have 3 options for getting o into your C2 instance:

  1. pass it in the constructor
  2. use a setter method
  3. pass it directly as an argument to delegateLogic

Which of these you choose depends on many things.

Note that storing a reference to o in a member variable of the class does not force you to serialize that reference.

Upvotes: 2

Nat
Nat

Reputation: 3717

If you want C2 to be able to be serialized, just declare o as transient. However, you would need to accept the fact that o will be null if it got serialized/deserialized unless you manage to serialize it manually somehow.

public class X extends C2 {
    private transient Object o;

    public X(Object o) {
        this.o = o;
    }

    public void delegateLogic() {
        Object my_o = o;  // refrences main's local variable
        // huge method body
        // object o local to main is required here  
    }
}

Upvotes: 1

Related Questions