Question

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

Was it helpful?

Solution

Just don't make it anonymous. The point of anonymous classes is when you don't expect to reuse them. Pass the necessary final variable to the class via a constructor.

Other option is to allow doSomething to take the parameter instead of the constructor, if you want the anonymous class to be instantiated once. You will still need to make it not anonymous and it will need to be owned by the parent class but this allows you to only use one object. Whether this is good design depends on the specifics.

OTHER TIPS

Make the object the anonymous inner class references an instance of some wrapper class for the object that changes (e.g. one of the instance variables of the wrapper class is of type object, and just change that variable as needed).

do you mean

final Object[] param = { null };

Foo foo = new Foo() 
    void invoke() 
        use param[0]

param[0] = objA;
foo.invoke();

param[0] = objB;
foo.invoke();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top