I have this non-static inner class that causes memory leaks, because it holds an implicit reference to the enclosing class:
private class CalendarScheduleUpdatedEventListener extends ScheduleUpdatedEventListener.Stub {
@Override
public void onScheduleUpdatedEvent() throws RemoteException {
updateCalendar();
}
}
In order to stop it from leaking, I need to make it static:
private static class CalendarScheduleUpdatedEventListener extends ScheduleUpdatedEventListener.Stub {
@Override
public void onScheduleUpdatedEvent() throws RemoteException {
updateCalendar();-> Compiler error - trying to access a non-static...
}
}
It is impossible to make updateCalendar()
static because in it I access other non-static variables and it becomes a mess. What do I do?
Having static members in inner class. You cannot have members of a non-static inner class static. Static methods are allowed only in top-level classes and static inner classes.
Non-static nested classes have full access to the class members in which it is created. A single instance of the outer class can be associated with more than one instances of the inner class. The keyword ”this” can be used in the non-static method to refer to the current object.
If you want to access the static members of a class, then you need to access them using the class name whereas you need an instance of a class to access the non-static members. Console.WriteLine("Press any key to exit.");
Since nested classes were first introduced to Java, with the exception of static final fields initialized by constant expressions, nested class declarations that are inner have been prohibited from declaring static members. This restriction applies to non-static member classes, local classes, and anonymous classes.
You need to pass in a reference to an instance of your outer class. And you need to make your static class public.
public static class CalendarScheduleUpdatedEventListener extends ScheduleUpdatedEventListener.Stub {
@Override
public void onScheduleUpdatedEvent(final TheOuterClass instance) throws RemoteException {
instance.updateCalendar();
}
}
private static class CalendarScheduleUpdatedEventListener extends ScheduleUpdatedEventListener.Stub {
final WeakReference<Object> obj; //change <Object> to whatever type it is.
CalendarScheduleUpdatedEventListener(Object x) {
this.obj = new WeakReference<>(x);
}
@Override
public void onScheduleUpdatedEvent() throws RemoteException {
Object o = obj.get();
if (o == null) {
//because a WeakReference will be null if it has been garbage collected.
return; //or throw some exception
}
o.updateCalendar();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With