Dynamic proxy for concrete classes - java

I want to define a method interceptor in a Java program in other words I want to have a behaviour which is executed at each method call.
This application isn't executed in an application server and therefore I can't use the EJB around invoke interceptors.
I have found a nice Proxy API in the standard Java libraries but its limited because it needs an interface in the proxy creation:
Foo f = (Foo) Proxy.newProxyInstance(Foo.class.getClassLoader(),
new Class[] { Foo.class },
handler);
Is there a similar API which doesn't force Foo.class to be declared as an interface?

Why not use CGLIB ? See this article for more information.
What if you want to proxy legacy classes that do not have interfaces?
You can use CGLIB. CGLIB is a powerful, high-performance code
generation library. Under the cover, it uses ASM, a small but fast
bytecode manipulation framework, to transform existing byte code to
generate new classes. CGLIB is faster than the JDK dynamic proxy
approach. Essentially, it dynamically generates a subclass to override
the non-final methods of the proxied class and wires up hooks that
call back to the user-defined interceptors.

Unfortunately there is no such API for classes. Many frameworks are using bytecode generation libraries like CGLIB to achieve this.

You can try one of the mocking classes. The simplest approach may be to sub-class, your class. Or you could use AOP to inject the logging code you want.

sun.misc.ProxyGenerator can be used to generate proxy classes and doesn't check that their "interfaces" are all interfaces. Its generateClassFile method gives you the bytecode as a byte array, which you can save to link into future builds or alter with third-party tools.
Note that if any of the "interfaces" has a final method, you'll get an error when you try to load the class.

Related

Java JSR-303 Automatic Bean Validation without Byte Code Weaving

Is there a way to perform (more or less) "automatic" JSR-303 java bean validation without runtime modification of a class?
Usually I see people using AspectJ to accomplish this, but we have had so many complications when using runtime code weaving (like with cofoja) that I'd like to avoid it. It makes a lot of our build tools fail because the runtime class files were different than the class files on disk.
I've looked at dynamic proxies via reflection which can only proxy interfaces (public methods) AND if you call anything annotated inside "this", you don't go through the proxy anymore so you lose that validation.
I'v also looked at ByteBuddy for a way to possibly intercept method calls by wrapping/redefining a class. There might be something here but I can't figure out how to intercept private methods or accomplish the above without getting back into modifying the original class.
Any ideas?
In theory, you can enforce bean validation by reflection only. But I assume that by automatic, you mean without an explicit call to a validation method.
In this case, instrumentation is probably your only option. With Byte Buddy, you can instrument existing methods, by using redefinition or rebasing. The easiest way to do so is a Java agent using an agent builder or using the Gradle or Maven plugins for build time instrumentation. The documentation provides an example of how to implement an agent and the build instrumentations have a lot of javadoc (documentation in progress).

What is the difference between JDK dynamic proxy and CGLib?

In case of the Proxy Design Pattern, What is the difference between JDK's Dynamic Proxy and third party dynamic code generation API s such as CGLib?
What is the difference between using both the approaches and when should one prefer one over another?
JDK Dynamic proxy can only proxy by interface (so your target class needs to implement an interface, which is then also implemented by the proxy class).
CGLIB (and javassist) can create a proxy by subclassing. In this scenario the proxy becomes a subclass of the target class. No need for interfaces.
So Java Dynamic proxies can proxy: public class Foo implements iFoo where CGLIB can proxy: public class Foo
EDIT:
I should mention that because javassist and CGLIB use proxy by subclassing, that this is the reason you cannot declare final methods or make the class final when using frameworks that rely on this. That would stop these libraries from allowing to subclass your class and override your methods.
Differences in functionality
The JDK proxies allow to implement any set of interfaces while subclassing Object. Any interface method, plusObject::hashCode, Object::equals and Object::toString is then forwarded to an InvocationHandler. Additionally, the standard library interface java.lang.reflect.Proxy is implemented.
cglib allows you to implement any set of interfaces while subclassing any non-final class. Also, methods can be overridden optionally, i.e. not all non-abstract methods need to be intercepted. Furthermore, there are different ways of implementing a method. It also offers an InvocationHandler class (in a different package), but it also allows to call super methods by using more advanced interceptors as for example a MethodInterceptor. Furthermore, cglib can improve performance by specialized interceptions like FixedValue. I once wrote a summary of different interceptors for cglib.
Performance differences
JDK proxies are implemented rather naively with only one interception dispatcher, the InvocationHandler. This requires a virtual method dispatch to an implementation which cannot always be inlined. Cglib allows to create specialized byte code what can sometimes improve performance. Here are some comparisons for implementing an interface with 18 stub methods:
cglib JDK proxy
creation 804.000 (1.899) 973.650 (1.624)
invocation 0.002 (0.000) 0.005 (0.000)
The time is noted in nanoseconds with standard deviation in braces. You can find more details on the benchmark in Byte Buddy's tutorial, where Byte Buddy is a more modern alternative to cglib. Also, note that cglib is no longer under active development.
Dynamic proxy: Dynamic implementations of interfaces at runtime using JDK Reflection API.
Example: Spring uses dynamic proxies for transactions as follows:
The generated proxy comes on top of bean. It adds transnational behavior to the bean. Here the proxy generates dynamically at runtime using JDK Reflection API.
When an application is stopped, the proxy will be destroyed and we will only have interface and bean on the file system.
In the above example we have interface. But in most of implementation of interface is not best. So bean does not implement an interface, in that case we uses inheritance:
In order to generate such proxies, Spring uses a third party library called CGLib.
CGLib (Code Generation Library) is built on top of ASM, this is mainly used the generate proxy extending bean and adds bean behavior in the proxy methods.
Examples for JDK Dynamic proxy and CGLib
Spring ref
From Spring documentation :
Spring AOP uses either JDK dynamic proxies or CGLIB to create the
proxy for a given target object. (JDK dynamic proxies are preferred
whenever you have a choice).
If the target object to be proxied implements at least one interface
then a JDK dynamic proxy will be used. All of the interfaces
implemented by the target type will be proxied. If the target object
does not implement any interfaces then a CGLIB proxy will be created.
If you want to force the use of CGLIB proxying (for example, to proxy
every method defined for the target object, not just those implemented
by its interfaces) you can do so. However, there are some issues to
consider:
final methods cannot be advised, as they cannot be overriden.
You will need the CGLIB 2 binaries on your classpath, whereas dynamic
proxies are available with the JDK. Spring will automatically warn you
when it needs CGLIB and the CGLIB library classes are not found on the
classpath.
The constructor of your proxied object will be called twice. This is a
natural consequence of the CGLIB proxy model whereby a subclass is
generated for each proxied object. For each proxied instance, two
objects are created: the actual proxied object and an instance of the
subclass that implements the advice. This behavior is not exhibited
when using JDK proxies. Usually, calling the constructor of the
proxied type twice, is not an issue, as there are usually only
assignments taking place and no real logic is implemented in the
constructor.

Javassist. What is the main idea and where real use?

I know that Javassist is a Java library providing a means to manipulate the Java bytecode of an application.
Ok, but why we need manipulate bytecode?
Any real example?
Any real app, where javassist used?
A common application is to generate proxy classes at runtime, i.e. to create a subclass at runtime that intercepts all method invocations. Examples:
Hibernate uses Proxies to intercept method invocations on entities to implement lazy loading, i.e. fetching the object from the database when it is first accessed.
The Spring Framework uses Proxies to implement its AOP support, which among other things powers its support for declarative transactions. It also uses proxies to enforce proper scoping.
EJB uses proxies to implement container managed transactions, authorization checking, and to apply user-defined interceptors.
CDI implementations must also proxy the managed beans to ensure proper scoping. I suspect they use a byte code engineering library, too.
I recently used Javassist to implement a transparent cache for method return values, by intercepting all method invocations and only delegating to the super implementation on the first invocation.
Note that java.lang.reflect.Proxy can generate proxy classes at runtime, but can only implement interfaces, not extend a class. All of the above use cases require the proxying of classes.
Bytecode manipulation is useful and necessary, especially when you do not have source code for certain projects. Say you only have the bytecode (like a jar file) for some project, but you want somehow change the behavior of the code, the bytecode manipulation library can help in such cases. The advantage of bytecode manipulation is that you don't need to recompile your code and can directly execute it after manipulation.
I have used bytecode manipulation to do some program analysis. Given a library, I want to know during the runtime what methods in the library have been invoked. I can use bytecode manipulation to insert a System.out.println("method_name"); statement in the beginning of a method. So during the runtime, it will print out what methods have been invoked.
Some bytecode manipulation libraries are:
ASM
ByteBuddy
BCEL
To extend Meriton answer and to provide a real example of use :
Hibernate-core (5.2.8.Final) use javaassit (3.20.0-GA):
https://mvnrepository.com/artifact/org.hibernate/hibernate-core/5.2.8.Final
Users page of the ASM project lists several dozen widely used Java projects and frameworks using ASM for bytecode analysis and manipulation. http://asm.ow2.org/users.html

What is the easiest way to generate an efficient implementation of a Java interface at runtime?

Starting with one Java base-interface, I want others to be able to extend this interface, directly or indirectly, and add bean properties and behavior to it, as a plugin system.
Then, at runtime, on the user computer, I would find all those interfaces and generate a single big class that implements them all. The fields required for the bean properties would be generated automatically, while the behavior defined in the interfaces would be implemented as static methods of an helper class (created by the plugin developers) that take the appropriate interface as first parameter, so the implementation of the interface method would delegate to a static method, passing "this" as first parameter.
This is similar to how Scala implements it's traits.
I see 3 ways of doing this:
Use Java's dynamic proxies, which are based on reflection.
Generate the source-code as a string, and compile it at runtime.
Use some bytecode manipulation library to generate the class at runtime.
Option 1 is the easiest, but least efficient, and therefore I want a better solution. Option 2 would give me an efficient implementation, but is rather ugly.
While I have seen several libraries that can do option 3, they all seem to require that I learn Java's assembler language first, which I take as a very time-consuming activity, with little benefits in the end..
Since I don't want to learn any assembler, JVM or otherwise, is option 2 my best bet, or are there libraries that can generate dynamic proxies without me using JVM assembler?
Have a look at Javassist. With it, you can make runtime changes to classes using a straight-forward API. You don't need to know about java "black magic" to use it.
When using BCEL you don't have to know java assembler. Lok at this proxy.

How is AOP being implemented to Change Java interface content?

I am current using Seasar2 Framework on a project that I am in. The framework is quite popular here in Japan but I am having problem in finding English documentations. Even on their official English translation site, they just discuss that the framework use Dependency Injection and AOP.
I was intrigued with the way they use it in one of their component S2Dao. Basically you only need to create interface DAO class and the framework automatically, changes the code on runtime and creates intermediate class that get called in the middle. Hence DB transactions codes are automatically added to the class. I was wondering, is there any step by step explanation on how this is done? Can java change code on runtime and change the method on runtime?
Are good reference on how this is done? I just want to know how the framework is doing this.
Yes, it is possible to do dynamic implementations of an interface at runtime, and to manipulate the compiled bytecode also.
Java provides a built-in mechanism to implement interfaces at run-time, called dynamic proxy classes.
There are also good libraries like cglib or javassist, that allow you not only to implement interfaces, but also to extend classes and to manipulate bytecode at run-time (to change the behavior of a method, for example). Frameworks like Spring and Hibernate use libraries like these to make their magic, so your framework may be using some of these also.
NOTE: If you are curious, these libraries can "tweak" the bytecode because instead of using the default ClassLoader of the JVM, they load your classes using their own ClassLoader, so they have total control of every single byte of the loaded class, and they can do whatever they want with them :).

Categories