0

I currently use Javaassist to generate a proxy for a class:

ProxyFactory f = new ProxyFactory();
f.setSuperclass(JFrame.class); // Just an example.

// I would like to create a proxy for JFrame to
// fill with method implementations...
f.setHandler(handler); // ... in an own handler

Class<?> proxyClazz = f.createClass();

My problem is: The JFrame constructor is also called. Makes sense. But I dont want this. I would like to generate an empty class as proxy which is assign-compatible to other normal JFrames.

Is there a way to do this? Thank you for all ideas and thoughts.

5
  • 1
    No, the superclass constructor has to be called. Commented Nov 7, 2017 at 8:29
  • Not really. There is 3 different way to create class without invoking constructor. Commented Nov 7, 2017 at 8:33
  • @talex : you meant create object instance of given class type when you said create class ? Commented Nov 7, 2017 at 10:07
  • @rkosegi yes. Exactly. Commented Nov 7, 2017 at 10:09
  • Isn't this achievable using built-in JDK Proxy and InvocationHandler ? Commented Nov 7, 2017 at 10:15

1 Answer 1

1
  1. Serialization

You can create array of bytes representing required class in serialized form and use ObjectInputStream.readObject.

This is possible but it is hard to prepare correct data.

  1. NativeConstructorAccessorImpl

This is how spy method is implemented in mockito.

  1. Unsafe.allocateInstance

So you prepare your proxy class and instantiate it one of those method (or some other way).

PS: Take a look on objenesis library.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you talex! This is exactly what I searched for!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.