I need to create anonymous inner types that are expensive to build and need to acces a final variable in it. The problem is that I need to create many of them with the only difference that the used final variable is different (object itself and type).
Is it possible to do this in a more reusable manner?
A simple example:
final Object aNeededParameter = "test";
Object expensiveToBuild = new ExpensiveInnerType() {
public void doSomething() {
aNeededParameter.toString();
}
});
I need instances of expensiveToBuild for different Objects at the same time, for example 1L, new Date(), "another similar usecase"
The basic idea is to create proxies for different serialized instances of concrete classes at runtime, that deserialize this objects on first usage. I made a working example (link at the bottom) but the proxy creation is very expensive.
There is a ProxyFactory that needs a MethodHandler to create a Proxy object via bytecode-enhancement. The MethodHandler defines a Method
invoke(Object self, Method realMethod, Method proxyMethod, Object[] args) throws Throwable
In my case this method needs access to a byte[] containing the serialized object the proxy is build for. So I have to create a new MethodHandler and build/compile a new Proxy object for each object I want a proxy for.
The invoke method is called automatically before every method call on the original object and simply checks if that object initialized and deserializes it if not. After that it invokes the called method on the original object.
If you want to see the concrete usecase look here:
Lazy deserializationproxy for java