Why the create method of Javassist ProxyFactory does not invoke the right constructor based on the args parameter?

StackOverflow https://stackoverflow.com/questions/15482534

  •  24-03-2022
  •  | 
  •  

Question

Consider the following class declaration:

class A{
    private String x;
    public A(String x) {
            this.x = x;
    }
}

When I try to create a proxy for the class A with the javassist with the following code:

ProxyFactory factory = new ProxyFactory();
factory.setSuperclass(A.class);
MethodHandler mh = new MethodHandler() {...};
A a = (A) factory.create(new Class<?>[0], new String(){"hello"}, mh);

then I got java.lang.RuntimeException: java.lang.NoSuchMethodException: app.test.A_$$_javassist_0.<init>()

Why javassist does not instantiate the class A using the correct constructor based on the type of the parameters of the second argument passed to the create method?

Was it helpful?

Solution 2

You can replace the last statement by:

Class proxyKlass = factory.createClass();
Constructor<T> ctor = proxyKlass.getConstructor(String.class);
T res = ctor.newInstance(new String(){"hello"});
((Proxy) res).setHandler(handler);

OTHER TIPS

By passing new Class<?>[0], you are telling the factory to call the no-args constructor. Try:

factory.create(new Class<?>[] { String.class }, new String[]{ "hello" }, mh);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top