Creating a Java Proxy instance for a class type?

I have the following code that works to create a Proxy instance for the type of interface supported by the InvocationHandler implementation, however, when I use a specific class type, it does not work, and this is well known and documented in Proxy.newProxyInstance :

  // NOTE: does not work because SomeConcreteClass is not an interface type final ClassLoader myClassLoader = SomeConcreteClass.getClassLoader(); SomeConcreteClass myProxy = (SomeConcreteClass) Proxy.newProxyInstance(myClassLoader, new Class[] { SomeConcreteClass.class }, new InvocationHandler() { /* TODO */ }); 

However, if I remember correctly, I saw this use case in some mock frameworks where you can mock a particular type of class, for example. EasyMock . Before checking the source code, can anyone specify what needs to be done for the proxy, as well as specific types of classes, not just interfaces?

+6
source share
1 answer

JDK dynamic proxies only work with interfaces. If you want to create a proxy with a specific superclass, you need to use something like CGLIB instead .

 Enhancer e = new Enhancer(); e.setClassLoader(myClassLoader); e.setSuperclass(SomeConcreteClass.class); e.setCallback(new MethodInterceptor() { public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable { return proxy.invokeSuper(obj, args); } }); // create proxy using SomeConcreteClass() no-arg constructor SomeConcreteClass myProxy = (SomeConcreteClass)e.create(); // create proxy using SomeConcreteClass(String) constructor SomeConcreteClass myProxy2 = (SomeConcreteClass)e.create( new Class<?>[] {String.class}, new Object[] { "hello" }); 
+12
source

All Articles