简体   繁体   中英

How can I make a java.lang.reflect.Proxy from two separate classloaders?

I use the CXF JAXRSClientFactory to create proxy instances out of various JAX-RS interfaces. Deep inside, this factory invokes Proxy.newProxyInstance(), passing in my interface and the CXF Client interface.

Under OSGi, this works great if the bundle that contains my interface class imports org.apache.cxf.jaxrs.client. But one day I decided I wanted to hide CXF from my application classes, so I created a bundle that encapsulates the client factory in a service. Now I get IllegalArgumentException from Proxy saying "MyInterface is not visible from class loader" or "Client is not visible from class loader".

The issue is that my factory bundle imports CXF but not my application. And my application bundle does not import CXF. So there's no classloader anywhere in the container that can see both the CXF Client class and my JAX-RS interface.

Is there a way to solve this without importing CXF into my application bundles? For example, could my factory bundle dynamically make a new classloader that's the union of the two classloaders, so it can see both CXF and my application classes? Or can I fool Proxy into accepting the two interfaces anyway?

This is now a solvable problem as of CXF 2.6.1. The closed issue CXF-4290 adds a new API to pass a custom classloader to JAXRSClientFactory. With that and the new org.apache.cxf.jaxrs.client.ProxyClassLoader class, I can now make proxies for arbitrary application classes.

    ProxyClassLoader classLoader = new ProxyClassLoader();
    classLoader.addLoader(resourceApiClass.getClassLoader());
    classLoader.addLoader(JAXRSClientFactoryBean.class.getClassLoader());

    JAXRSClientFactoryBean bean = new JAXRSClientFactoryBean();
    bean.setAddress(baseUrl);
    bean.setServiceClass(resourceApiClass);
    bean.setClassLoader(classLoader);
    return bean.create(resourceApiClass);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM