1

I'm trying to make the tricky thing. I have method ObjectFactory.getObject() which returns an Object that needs to implement Serializable. I'm trying to make a proxy of an already existing instance of ObjectFactory, intercept its method getObject() and then wrap returned object to a proxy, which implements Serializable.

@Override
public Object get(String name, ObjectFactory<?> objectFactory) {

    ...

    ObjectFactory<?> serializableObjectFactory = (ObjectFactory<?>)Proxy.newProxyInstance(CurrentClass.class.getClassLoader(), new Class[]{ObjectFactory.class}, new InvocationHandler() {
        @Override
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            //Here I'm getting StackOverflow exception. I guess, it just invokes itself recursively. Don't know why
            Object result = ((ObjectFactory<?>) proxy).getObject();

            //Here I make object implement Serializable
            return Mixin.create(new Class[]{Serializable.class, result.getClass()}, new Object[] {result});
        }
    });

    ...

    return super.get(name, serializableObjectFactory);
}

When code comes to Object result = ((ObjectFactory<?>) proxy).getObject() it seems just invokes itself recursively(I'm getting StackOverflow exception) and I have no idea why.

I have two guesses about which I can't be sure:

  1. I use proxy in the wrong way. But I checked and it seems to be fine.
  2. Object proxy in method invoke() comes as a proxy so it might invoke itself in an endless loop. I didn't find how to unwrap this proxy to a real object besides Advise, but it doesn't suit this proxy.

Do you have any guesses what's wrong?

Woods
  • 119
  • 1
  • 12

1 Answers1

1

Let's take a look at this line:

Object result = ((ObjectFactory<?>) proxy).getObject();

What do you think is going to happen?

  1. It invokes the proxy.
  2. The proxy invokes your InvocationHandler.
  3. Go back to step 1.

Maybe call the method on objectFactory instead?

Johannes Kuhn
  • 14,778
  • 4
  • 49
  • 73