Search code examples
javajavassist

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


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?


Solution

  • 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);