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

假装没事ソ 提交于 2019-11-28 16:00:18

问题


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?


回答1:


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.




回答2:


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



回答3:


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




回答4:


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



来源:https://stackoverflow.com/questions/7297565/javassist-what-is-the-main-idea-and-where-real-use

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!