Skip to content

Instantly share code, notes, and snippets.

@cor3000
Last active March 8, 2021 02:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cor3000/0e178634234ed544a6790df404143f82 to your computer and use it in GitHub Desktop.
Save cor3000/0e178634234ed544a6790df404143f82 to your computer and use it in GitHub Desktop.
package zk.example.devconfig;
import org.zkoss.bind.BindComposer;
import org.zkoss.bind.impl.BinderImpl;
import org.zkoss.zel.BeanELResolver;
import org.zkoss.zel.impl.util.ConcurrentCache;
import org.zkoss.zk.ui.Desktop;
import org.zkoss.zk.ui.Execution;
import org.zkoss.zk.ui.util.DesktopInit;
import org.zkoss.zk.ui.util.ExecutionInit;
import java.lang.reflect.Field;
import java.util.Map;
public class AutoClearCaches implements DesktopInit, ExecutionInit {
/**
* pick this if you want to clear the caches only once per page refresh (F5)
*/
@Override
public void init(Desktop desktop, Object o) throws Exception {
// clearBeanElResolverCache();
// clearMvvmCaches();
}
/**
* pick this if you want to clear the caches with every Execution
* this allows code changes to MVVM annotated methods and bean properties without having to reload a page
*/
@Override
public void init(Execution execution, Execution parent) throws Exception {
if(parent == null) {
clearBeanElResolverCache();
clearMvvmCaches();
}
}
public static void clearMvvmCaches() throws Exception {
clearMap(BinderImpl.class, "_initMethodCache");
clearMap(BinderImpl.class, "_destroyMethodCache");
clearMap(BinderImpl.class, "_commandMethodCache");
clearMap(BinderImpl.class, "_globalCommandMethodCache");
clearMap(BindComposer.class, "_afterComposeMethodCache");
clearMap(BindComposer.class, "_historyPopStateMethodCache");
}
public static void clearBeanElResolverCache() throws Exception {
ConcurrentCache cache = getField(BeanELResolver.class, "cache");
clearMap(cache, "longterm");
clearMap(cache, "eden");
}
private static void clearMap(Object obj, String fieldName) throws Exception {
Map map = getField(obj, fieldName);
System.out.println(String.format("Clearing map '%s' on %s (%s)", fieldName, obj, map));
map.clear();
}
private static <T> T getField(Object obj, String fieldName) throws Exception {
Class cls = obj instanceof Class ? (Class) obj : obj.getClass();
Field field = cls.getDeclaredField(fieldName);
field.setAccessible(true);
return (T) field.get(obj);
}
}
<zk>
<!-- enable listener -->
<listener>
<listener-class>zk.example.devconfig.AutoClearCaches</listener-class>
</listener>
</zk>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment