Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alternatives to Java bytecode instrumentation

I'm starting a project that will have to instrument java applications for coverage purposes (definition-usage of variables, etc). It has to add trace statements and some logic to the application and maybe remove statements.

I have searched for ways of instrument Java code and what I always find is about bytecode instrumentation.

My question is: It's the only way to instrument Java applications? There is any other way to do that? What are the advantages of bytecode instrumentation over the others?

I'll probably use the bytecode solution, but I want to know what are the problems with the other approaches (if any) to decide precisely.

Thanks!

like image 771
Rafael Regis Avatar asked Jul 24 '12 20:07

Rafael Regis


People also ask

What is bytecode instrumentation in Java?

Bytecode instrumentation is a process where new function- ality is added to a program by modifying the bytecode of a set of classes before they are loaded by the virtual machine. This paper will look into the details of bytecode instrumen- tation in Java: the tools, APIs and real-life applications.

What is ASM package?

ASM is an all purpose Java bytecode manipulation and analysis framework. It can be used to modify existing classes or to dynamically generate classes, directly in binary form.

What is bytecode manipulation?

Bytecode manipulation consists in modifying the classes - represented by bytecode - compiled by the Java compiler, at runtime. It is used extensively for instance by frameworks such as Spring (IoC) and Hibernate (ORM) to inject dynamic behaviour to Java objects at runtime.


1 Answers

The other method close to changing bytecode is using AOP (Aspect Oriented Programming). The main library is AspectJ which also mostly defines the area.

The third option that might be interesting (since you are just starting out with the program) is using Spring. It means you will have to learn a bit about IOC (inversion of control) but it basically means that instead of creating your objects yourself you let spring do it for you, and it has it advantages because when spring is incharge of the creation it can add all sorts of things in the creation process without you having to really declare it all yourself in aspectj.

In terms of complexity I would probably rate it:

  • spring (easiest)
  • aspectj
  • bytecode instrumentation (hardest)

but it's exactly the other way around when talking about capabilities (power). for example doing something like substracting code is only possible using the last one (I think)

like image 72
arikg Avatar answered Sep 24 '22 16:09

arikg