Reputation: 2977
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 :
Any ideas?
Upvotes: 1
Views: 133
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:
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
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