<?xml version="1.0" encoding="utf-8"?>
<?xml-stylesheet type="text/xsl" href="https://www.niceideas.ch/roller2/roller-ui/styles/rss.xsl" media="screen"?><rss version="2.0" 
  xmlns:dc="http://purl.org/dc/elements/1.1/"
  xmlns:atom="http://www.w3.org/2005/Atom" >
<channel>
  <title>niceideas.ch</title>
  <link>https://www.niceideas.ch/roller2/badtrash/</link>
      <atom:link rel="self" type="application/rss+xml" href="https://www.niceideas.ch/roller2/badtrash/feed/entries/rss?cat=Java" />
    <description>Technological Thoughts by Jerome Kehrli</description>
  <language>en-us</language>
  <copyright>Copyright 2026</copyright>
  <lastBuildDate>Thu, 9 Apr 2026 06:13:17 -0400</lastBuildDate>
  <generator>Apache Roller 5.1.2</generator>
        <item>
    <guid isPermaLink="true">https://www.niceideas.ch/roller2/badtrash/entry/bytecode-manipulation-with-javassist-for1</guid>
    <title>Bytecode manipulation with Javassist for fun and profit part II: Generating toString and getter/setters using bytecode manipulation</title>
    <dc:creator>Jerome Kehrli</dc:creator>
    <link>https://www.niceideas.ch/roller2/badtrash/entry/bytecode-manipulation-with-javassist-for1</link>
        <pubDate>Mon, 24 Apr 2017 16:38:42 -0400</pubDate>
    <category>Java</category>
    <category>bytecode-manipulation</category>
    <category>javassist</category>
    <category>lombok</category>
    <atom:summary type="html">&lt;p&gt;
Following my first article on Bytecode manipulation with Javassist presented there: &lt;a href=&quot;https://www.niceideas.ch/roller2/badtrash/entry/bytecode-manipulation-with-javassist-for&quot;&gt;Bytecode manipulation with Javassist for fun and profit part I: Implementing a lightweight IoC container in 300 lines of code&lt;/a&gt;, I am here presenting another example of Bytecode manipulation with Javassist: generating &lt;code&gt;toString&lt;/code&gt; method as well as property getters and setters with Javassist.
&lt;/p&gt;
&lt;p&gt;
While the former example was oriented towards understanding how Javassist and bytecode manipulation comes in help with implementing IoC concerns, such as what is done by the spring framework of the pico IoC container, this new example is oriented towards generating &lt;i&gt;boilerplate code&lt;/i&gt;, in a similar way to what &lt;a href=&quot;https://projectlombok.org/&quot;&gt;Project Lombok&lt;/a&gt; is doing.
&lt;br&gt;
As a matter of fact, generating boilerplate code is another very sound use case for bytecode manipulation.
&lt;/p&gt;
&lt;p&gt;
Boilerplate code refers to portions of code that have to be included or written in the same way in many places with little or no alteration. 
&lt;br&gt;
The term is often used when referring to languages that are considered verbose, i.e. the programmer must write a lot of code to do minimal job. And Java is unfortunately a clear winner in this regards.
&lt;br&gt;
Avoiding boilerplate code is one of the main reasons (but by far not the only one of course !) why developers are moving away from Java in favor of other JVM languages such as Scala.
&lt;/p&gt;
&lt;p&gt;
In addition, as a reminder, a sound understanding of the Java Bytecode and the way to manipulate it are strong prerequisites to software analytics tools, mocking libraries, profilers, etc. Bytecode manipulation is a key possibility in this regards, thanks to the JVM and the fact that bytecode is interpreted.
&lt;br&gt;
Traditionally, bytecode manipulation libraries suffer from complicated approaches and techniques. Javassist, however, proposes a natural, simple and efficient approach bringing bytecode manipulation possibilities to everyone.
&lt;/p&gt;
&lt;p&gt;
So in this second example about Javassist we&apos;ll see how to implement typical &lt;i&gt;Lombok&lt;/i&gt; features using Javassist, in a few dozen lines of code.
&lt;/p&gt;</atom:summary>        <description>&lt;!-- Bytecode manipulation with Javassist for fun and profit part II: Generating toString and getter/setters using bytecode manipulation --&gt;

&lt;p&gt;
Following my first article on Bytecode manipulation with Javassist presented there: &lt;a href=&quot;https://www.niceideas.ch/roller2/badtrash/entry/bytecode-manipulation-with-javassist-for&quot;&gt;Bytecode manipulation with Javassist for fun and profit part I: Implementing a lightweight IoC container in 300 lines of code&lt;/a&gt;, I am here presenting another example of Bytecode manipulation with Javassist: generating &lt;code&gt;toString&lt;/code&gt; method as well as property getters and setters with Javassist.
&lt;/p&gt;
&lt;p&gt;
While the former example was oriented towards understanding how Javassist and bytecode manipulation comes in help with implementing IoC concerns, such as what is done by the spring framework of the pico IoC container, this new example is oriented towards generating &lt;i&gt;boilerplate code&lt;/i&gt;, in a similar way to what &lt;a href=&quot;https://projectlombok.org/&quot;&gt;Project Lombok&lt;/a&gt; is doing.
&lt;br&gt;
As a matter of fact, generating boilerplate code is another very sound use case for bytecode manipulation.
&lt;/p&gt;
&lt;p&gt;
Boilerplate code refers to portions of code that have to be included or written in the same way in many places with little or no alteration. 
&lt;br&gt;
The term is often used when referring to languages that are considered verbose, i.e. the programmer must write a lot of code to do minimal job. And Java is unfortunately a clear winner in this regards.
&lt;br&gt;
Avoiding boilerplate code is one of the main reasons (but by far not the only one of course !) why developers are moving away from Java in favor of other JVM languages such as Scala.
&lt;/p&gt;
&lt;p&gt;
In addition, as a reminder, a sound understanding of the Java Bytecode and the way to manipulate it are strong prerequisites to software analytics tools, mocking libraries, profilers, etc. Bytecode manipulation is a key possibility in this regards, thanks to the JVM and the fact that bytecode is interpreted.
&lt;br&gt;
Traditionally, bytecode manipulation libraries suffer from complicated approaches and techniques. Javassist, however, proposes a natural, simple and efficient approach bringing bytecode manipulation possibilities to everyone.
&lt;/p&gt;
&lt;p&gt;
So in this second example about Javassist we&apos;ll see how to implement typical &lt;i&gt;Lombok&lt;/i&gt; features using Javassist, in a few dozen lines of code.
&lt;/p&gt;
&lt;p&gt;
Part of this article is available as a slideshare presentation here: &lt;a href=&quot;https://www.slideshare.net/JrmeKehrli/bytecode-manipulation-with-javassist-for-fun-and-profit&quot;&gt;https://www.slideshare.net/JrmeKehrli/bytecode-manipulation-with-javassist-for-fun-and-profit&lt;/a&gt;.
&lt;/p&gt;
&lt;p&gt;
You might want to have a look at the first article in this serie available here : &lt;a href=&quot;https://www.niceideas.ch/roller2/badtrash/entry/bytecode-manipulation-with-javassist-for&quot;&gt;Bytecode manipulation with Javassist for fun and profit part I: Implementing a lightweight IoC container in 300 lines of code&lt;/a&gt;.
&lt;/p&gt;
&lt;p&gt;

&lt;b&gt;Summary&lt;/b&gt;
&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href=&quot;#sec1&quot;&gt;1. Introduction / Purpose &lt;/a&gt;&lt;/li&gt;

&lt;li&gt;&lt;a href=&quot;#sec2&quot;&gt;2. Javassist&lt;/a&gt;&lt;/li&gt;


&lt;li&gt;&lt;a href=&quot;#sec3&quot;&gt;3. Java Instrumentation framework and applications&lt;/a&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href=&quot;#sec31&quot;&gt;3.1 Lombok&lt;/a&gt;

&lt;ul&gt;

&lt;li&gt;&lt;a href=&quot;#sec311&quot;&gt;3.1.1 Example class&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;#sec312&quot;&gt;3.1.2 Without Lombok&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;#sec313&quot;&gt;3.1.3 With Lombok&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;#sec314&quot;&gt;3.1.4 Bytecode Manipulation vs. Code Generation&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;#sec315&quot;&gt;3.1.5 Just a note on concerns&lt;/a&gt;&lt;/li&gt;

&lt;/ul&gt;
&lt;/li&gt;

&lt;li&gt;&lt;a href=&quot;#sec32&quot;&gt;3.2 Java agents and the linkage problem&lt;/a&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href=&quot;#sec321&quot;&gt;3.2.1 Overcoming the Linkage problem with Java Agents&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;#sec322&quot;&gt;3.2.2 ClassFileTransformer&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;#sec323&quot;&gt;3.2.3 Caution&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;#sec324&quot;&gt;3.2.4 Simple Example&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;#sec325&quot;&gt;3.2.5 Invoking the Agent&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;#sec326&quot;&gt;3.2.6 Workaround&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;

&lt;/ul&gt;
&lt;/li&gt;

&lt;li&gt;&lt;a href=&quot;#sec4&quot;&gt;4.0 BCG: a simple approach for generating boilerplate code using Javassist&lt;/a&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href=&quot;#sec41&quot;&gt;4.1 Principle&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;#sec42&quot;&gt;4.2 Design&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;#sec43&quot;&gt;4.3 Implementation&lt;/a&gt;

&lt;ul&gt;

&lt;li&gt;&lt;a href=&quot;#sec431&quot;&gt;4.3.1 The code of the Agent&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;#sec432&quot;&gt;4.3.2 Interface ClassTransformer&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;#sec433&quot;&gt;4.3.3 Common Abstraction&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;#sec434&quot;&gt;4.3.4 The set of Class Transformers&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;#sec435&quot;&gt;4.3.5 Test Class Example&lt;/a&gt;&lt;/li&gt;

&lt;/ul&gt;
&lt;/li&gt;

&lt;/ul&gt;
&lt;/li&gt;

&lt;li&gt;&lt;a href=&quot;#sec5&quot;&gt;5. Conclusion&lt;/a&gt;&lt;/li&gt;

&lt;/ul&gt;




&lt;a name=&quot;sec1&quot;&gt;&lt;/a&gt;
&lt;h2&gt;1. Introduction / Purpose &lt;/h2&gt;

&lt;p&gt;
&lt;i&gt;I am giving only a few lines here and return the user to &lt;a href=&quot;https://www.niceideas.ch/roller2/badtrash/entry/bytecode-manipulation-with-javassist-for#sec1&quot;&gt;my first article on this topic&lt;/a&gt; for the complete introduction to bytecode manipulation.&lt;/i&gt;
&lt;/p&gt;
&lt;p&gt;
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. 
&lt;br&gt;
Bytecode manipulation is traditionally difficult. Out of all the various libraries and tools to achieve it, Javassist stands out due to its natural and simple yet efficient approach to it.
&lt;/p&gt;

&lt;a name=&quot;sec2&quot;&gt;&lt;/a&gt;
&lt;h2&gt;2. Javassist&lt;/h2&gt;

&lt;p&gt;
&lt;i&gt;I am giving only a few lines here and return the user to &lt;a href=&quot;https://www.niceideas.ch/roller2/badtrash/entry/bytecode-manipulation-with-javassist-for#sec2&quot;&gt;my first article on this topic&lt;/a&gt; for the complete introduction to Javassist.&lt;/i&gt;
&lt;/p&gt;
&lt;p&gt;
Quoting &lt;a href=&quot;&quot;&gt;Wikipedia&lt;/a&gt;:
&lt;/p&gt;
&lt;p&gt;
Javassist (Java programming assistant) is a Java library providing a means to manipulate the Java bytecode of an application.
&lt;/p&gt;
&lt;p&gt;
Javassist enables Java programs to define a new class at runtime and to modify a class file when the JVM loads it. Unlike other similar bytecode editors, Javassist provides two levels of API: source level and bytecode level. Using the source-level API, programmers can edit a class file without knowledge of the specifications of the Java bytecode; the whole API is designed with only the vocabulary of the Java language. Programmers can even specify inserted bytecode in the form of Java source text; Javassist compiles it on the fly. On the other hand, the bytecode-level API allows the users to directly edit a class file as other editors.
&lt;/p&gt;

&lt;a name=&quot;sec3&quot;&gt;&lt;/a&gt;
&lt;h2&gt;3. Java Instrumentation framework and applications&lt;/h2&gt;

&lt;p&gt;
Java 5 was the first version seeing the proper implementation of JSR-163 (Java Platform Profiling Architecture API) support including a bytecode instrumentation mechanism through the introduction of the Java Programming Language Instrumentation Services (JPLIS). At first that JSR only mentioned native (C) interfaces but evolved fast towards a pretty convenient Java API.
&lt;br&gt;
This was an interesting breakthrough since it allowed, with the help of an agent, to modify the content of a class bytecode inherent to the methods of a class in such a way as to modify its behavior at runtime.
&lt;/p&gt;
&lt;p&gt;
The key point of the JSR-163 is JVMTI. JVMTI - or Java Virtual Machine Tool Interface - allows a program to inspect the state and to control the execution of applications running in the Java Virtual Machine. JVMTI is designed to provide an &lt;i&gt;Application Programming Interface&lt;/i&gt; (API) for the development of tools that need access to the state of the JVM. Examples for such tools are debuggers, profilers or runtime boilerplate code generator.
&lt;/p&gt;
&lt;p&gt;
The scope of this article is to focus on presenting how a boilerplate code generator can benefit from JVMTI and bytecode manipulation to achieve unprecedented comfort and easiness of programming than ever before on the JVM, unless considering a different language than Java, such as Scala or Clojure.
&lt;/p&gt;
&lt;p&gt;
As a way to illustrate Boilerplate code concerns, We will focus on &lt;i&gt;Project Lombok&lt;/i&gt; and its features and try to see how to reproduce some of them using Javassist.
&lt;/p&gt;


&lt;a name=&quot;sec31&quot;&gt;&lt;/a&gt;
&lt;h3&gt;3.1 Lombok&lt;/h3&gt;

&lt;p&gt;
Project Lombok is a &lt;i&gt;Boilerplate code&lt;/i&gt; generator that addresses one of the most frequent criticism against the Java Programming Language: the volume of this type of code that is found in most projects.
&lt;br&gt;
&lt;i&gt;Boilerplate code&lt;/i&gt; is a term used to describe code that is repeated in many parts of an application with only slight contextual changes and with little added value.
&lt;br&gt;
Project Lombok reduces the need of some of the worst offenders by replacing each of them with a simple annotation. It then takes care of generating the boilerplate code at runtime
&lt;/p&gt;
&lt;p&gt;
Project Lombok also integrates well in IDEs making it possible to use the usual IDE features such as refactoring and usage analysis pretty transparently.
&lt;/p&gt;
&lt;p&gt;
Importantly in our context, since we will focus below on reproducing Lombok features using runtime bytecode generation, I have to mention right away that Lombok doesn&apos;t just generate Java sources or bytecode: it transforms the &lt;i&gt;Abstract Syntax Tree&lt;/i&gt; (AST), by modifying its structure at compile-time. 
&lt;br&gt;
The AST is a tree representation of the parsed source code, created by the compiler, similar to the DOM tree model of an XML file. By modifying (or transforming) the AST, Lombok keeps the source code trim and free of bloat, unlike plain-text code-generation. 
&lt;br&gt;
Lombok&apos;s generated code is also visible to classes within the same compilation unit, unlike direct bytecode manipulation. 
&lt;br&gt;
&lt;i&gt;Our approach, as we will see below, using runtime bytecode manipulation shall not benefit from the same comfort and is hence less efficient than what Lombok is doing.&lt;/i&gt;
&lt;/p&gt;

&lt;a name=&quot;sec311&quot;&gt;&lt;/a&gt;
&lt;h4&gt;3.1.1 Example class&lt;/h4&gt;

&lt;p&gt;
Let&apos;s see an example. Imagine the following Java POJO:
&lt;/p&gt;

&lt;pre&gt;
&lt;b&gt;public class&lt;/b&gt; DataExample {

    &lt;b&gt;private final&lt;/b&gt; String name;

    &lt;b&gt;private int&lt;/b&gt; age;

    &lt;b&gt;private double&lt;/b&gt; score;

    &lt;b&gt;private&lt;/b&gt; String[] tags;
}
&lt;/pre&gt;

&lt;p&gt;
Typical boilerplate code involved when considering such a POJO are:
&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Getters and Setters for all private fields, making them &lt;i&gt;JavaBean properties&lt;/i&gt;&lt;/li&gt;
&lt;li&gt;A nice &lt;code&gt;toString&lt;/code&gt; method giving the values of its properties when an object is output on the console&lt;/li&gt;
&lt;li&gt;Consistent &lt;code&gt;hashCode&lt;/code&gt; and &lt;code&gt;equals&lt;/code&gt; methods enabling to compare and manipulate two different objects with same values&lt;/li&gt;
&lt;li&gt;A default constructor without any argument (Javabean standard)&lt;/li&gt;
&lt;li&gt;An &lt;i&gt;all args&lt;/i&gt; constructor taking all values as argument to build the instance&lt;/li&gt;
&lt;/ul&gt;


&lt;a name=&quot;sec312&quot;&gt;&lt;/a&gt;
&lt;h4&gt;3.1.2 Without Lombok&lt;/h4&gt;

&lt;p&gt;
Without Lombok, writing all this code is a nightmare, and the simple class above becomes as follows:
&lt;/p&gt;

&lt;pre&gt;
&lt;b&gt;import&lt;/b&gt; java.util.Arrays;

&lt;b&gt;public class&lt;/b&gt; DataExample {

    &lt;b&gt;private final&lt;/b&gt; String name;
    &lt;b&gt;private int&lt;/b&gt; age;
    &lt;b&gt;private double&lt;/b&gt; score;
    &lt;b&gt;private&lt;/b&gt; String[] tags;
  
    &lt;b&gt;public&lt;/b&gt; DataExample(String name) {
        &lt;b&gt;this&lt;/b&gt;.name = name;
    }

    &lt;b&gt;public&lt;/b&gt; DataExample(String name, &lt;b&gt;int&lt;/b&gt; age, &lt;b&gt;double&lt;/b&gt; score, String[] tags) {
        &lt;b&gt;this&lt;/b&gt;.name = name;
        &lt;b&gt;this&lt;/b&gt;.age = age;
        &lt;b&gt;this&lt;/b&gt;.score = score;
        &lt;b&gt;this&lt;/b&gt;.tags = tags;
    }
  
    &lt;b&gt;public&lt;/b&gt; String getName() {
        &lt;b&gt;return this&lt;/b&gt;.name;
    }
  
    &lt;b&gt;void&lt;/b&gt; setAge(&lt;b&gt;int&lt;/b&gt; age) {
        &lt;b&gt;this&lt;/b&gt;.age = age;
    }
    &lt;b&gt;public int&lt;/b&gt; getAge() {
        &lt;b&gt;return this&lt;/b&gt;.age;
    }
  
    &lt;b&gt;public void&lt;/b&gt; setScore(&lt;b&gt;double&lt;/b&gt; score) {
        &lt;b&gt;this&lt;/b&gt;.score = score;
    }
    &lt;b&gt;public double&lt;/b&gt; getScore() {
        &lt;b&gt;return this&lt;/b&gt;.score;
    }
  
    &lt;b&gt;public&lt;/b&gt; String[] getTags() {
        &lt;b&gt;return this&lt;/b&gt;.tags;
    }
    &lt;b&gt;public void&lt;/b&gt; setTags(String[] tags) {
        &lt;b&gt;this&lt;/b&gt;.tags = tags;
    }
  
    @Override 
    &lt;b&gt;public&lt;/b&gt; String toString() {
        &lt;b&gt;return&lt;/b&gt; &lt;span style=&quot;color: blue;&quot;&gt;&quot;DataExample(&quot;&lt;/span&gt; + &lt;b&gt;this&lt;/b&gt;.getName() + 
            &lt;span style=&quot;color: blue;&quot;&gt;&quot;, &quot;&lt;/span&gt; + &lt;b&gt;this&lt;/b&gt;.getAge() + 
            &lt;span style=&quot;color: blue;&quot;&gt;&quot;, &quot;&lt;/span&gt; + &lt;b&gt;this&lt;/b&gt;.getScore() + 
            &lt;span style=&quot;color: blue;&quot;&gt;&quot;, &quot;&lt;/span&gt; + Arrays.deepToString(&lt;b&gt;this&lt;/b&gt;.getTags()) + &lt;span style=&quot;color: blue;&quot;&gt;&quot;)&quot;&lt;/span&gt;;
    }

    @Override 
    &lt;b&gt;public boolean&lt;/b&gt; equals(Object o) {
        &lt;b&gt;if&lt;/b&gt; (o == &lt;b&gt;this&lt;/b&gt;) &lt;b&gt;return true&lt;/b&gt;;
        &lt;b&gt;if&lt;/b&gt; (!(o &lt;b&gt;instanceof&lt;/b&gt; DataExample)) &lt;b&gt;return false&lt;/b&gt;;
        DataExample other = (DataExample) o;
        &lt;b&gt;if&lt;/b&gt; (&lt;b&gt;this&lt;/b&gt;.getName() == &lt;b&gt;null&lt;/b&gt; ? 
                other.getName() != &lt;b&gt;null&lt;/b&gt; : 
                !&lt;b&gt;this&lt;/b&gt;.getName().equals(other.getName())) 
            &lt;b&gt;return false&lt;/b&gt;;
        &lt;b&gt;if&lt;/b&gt; (&lt;b&gt;this&lt;/b&gt;.getAge() != other.getAge()) &lt;b&gt;return false&lt;/b&gt;;
        &lt;b&gt;if&lt;/b&gt; (Double.compare(&lt;b&gt;this&lt;/b&gt;.getScore(), other.getScore()) != 0) &lt;b&gt;return false&lt;/b&gt;;
        &lt;b&gt;if&lt;/b&gt; (!Arrays.deepEquals(&lt;b&gt;this&lt;/b&gt;.getTags(), other.getTags())) &lt;b&gt;return false&lt;/b&gt;;
        &lt;b&gt;return true&lt;/b&gt;;
    }
  
    @Override 
    &lt;b&gt;public int&lt;/b&gt; hashCode() {
        &lt;b&gt;final int&lt;/b&gt; PRIME = 59;
        &lt;b&gt;int&lt;/b&gt; result = 1;
        &lt;b&gt;final long&lt;/b&gt; temp1 = Double.doubleToLongBits(&lt;b&gt;this&lt;/b&gt;.getScore());
        result = (result*PRIME) + (&lt;b&gt;this&lt;/b&gt;.getName() == &lt;b&gt;null&lt;/b&gt; ? 43 : &lt;b&gt;this&lt;/b&gt;.getName().hashCode());
        result = (result*PRIME) + &lt;b&gt;this&lt;/b&gt;.getAge();
        result = (result*PRIME) + (&lt;b&gt;int&lt;/b&gt;)(temp1 ^ (temp1 &gt;&gt;&gt; 32));
        result = (result*PRIME) + Arrays.deepHashCode(&lt;b&gt;this&lt;/b&gt;.getTags());
        &lt;b&gt;return&lt;/b&gt; result;
    }
}
&lt;/pre&gt;

&lt;p&gt;
One needs to understand that while the features implemented by the code above are pretty useful and very important, the code itself has no added value whatsoever. Most IDEs generate this code for you using some right-click here and there. A machine can write this code for you, can you imagine this? ... And yet with java it HAS to be written. This makes no sense.
&lt;/p&gt;
&lt;p&gt;
So without Lombok, for a 4 properties, 5 lines of code class ... One has to write more than 60 lines of boilerplate code, that&apos;s a ratio of [Boilerplate code / Useful Code] of more than 1600% !!!
&lt;br&gt;
This is the main rationality behind project Lombok.
&lt;/p&gt;


&lt;a name=&quot;sec313&quot;&gt;&lt;/a&gt;
&lt;h4&gt;3.1.3 With Lombok&lt;/h4&gt;

&lt;p&gt;
With Lombok we can use the following set of annotations on top of the class to generate the very same boilerplate code that we had to write on our own above:
&lt;/p&gt;

&lt;pre&gt;
@Getter
@Setter
@ToString
@EqualsAndHashCode
@RequiredArgsConstructor
@AllArgsConstructor
&lt;b&gt;public class&lt;/b&gt; DataExample {

  &lt;b&gt;private final&lt;/b&gt; String name;

  &lt;b&gt;private int&lt;/b&gt; age;

  &lt;b&gt;private double&lt;/b&gt; score;

  &lt;b&gt;private&lt;/b&gt; String[] tags;
}
&lt;/pre&gt;

&lt;p&gt;
All these annotations are straightforward to understand so I won&apos;t be describing them any further.
&lt;/p&gt;
&lt;p&gt;
You might want to look at the &lt;a href=&quot;https://projectlombok.org/features/index.html&quot;&gt;Lombok documentation&lt;/a&gt; to learn more about these annotations.
&lt;/p&gt;
&lt;p&gt;
With Lombok, we get a much better ratio of boilerplate code concerns vs. useful code of 100% instead of more than 1600% without Lombok.
&lt;/p&gt;

&lt;a name=&quot;sec314&quot;&gt;&lt;/a&gt;
&lt;h4&gt;3.1.4 Lombok Apporoach (AST transformation) vs. Bytecode Manipulation vs. Code Generation&lt;/h4&gt;

&lt;p&gt;
&lt;b&gt;Code generation&lt;/b&gt;
&lt;/p&gt;
&lt;p&gt;
Of course there are alternatives to Lombok. For instance, most if not all IDEs enable the developer to generate these &lt;i&gt;boilerplate&lt;/i&gt; methods in the class source file just as Lombok does it.
&lt;br&gt;
But generating this code in the class source file is IMHO not the right approach. At the end of the day, I believe that &lt;b&gt;generated code&lt;/b&gt; - i.e. code that can be written by a machine - &lt;b&gt;should simply not be written&lt;/b&gt;! If a machine can write this code then this code has no added value at all! I do not want to see such code in my class files, I do not want to be aware of it.
&lt;br&gt;
Lombok generates this code transparently and seamlessly. By modifying (or transforming) the AST, Lombok keeps your source code trim and free of bloat, unlike plain-text code-generation.  With Lombok, I do not need to be aware of this code, it&apos;s not polluting my &lt;i&gt;code coverage&lt;/i&gt; computation (in Sonar for instance or else) and everything behaves &lt;i&gt;as if&lt;/i&gt; this code was actually written except that one doesn&apos;t see it and doesn&apos;t need to care about it.
&lt;/p&gt;
&lt;p&gt;
&lt;b&gt;Bytecode Manipulation&lt;/b&gt;
&lt;/p&gt;
&lt;p&gt;
Bytecode manipulation is preferable over Code generation IMHO in regards to generating (at least some of the) boilerplate code. For the same reason indicated above: bytecode manipulation makes the boilerplate code transparent and avoids it polluting my source code.
&lt;br&gt;
It is however not as efficient as AST Transformation such as Lombok is doing. Lombok&apos;s generated code is also visible to classes within the same compilation unit, unlike direct bytecode manipulation.
&lt;/p&gt;
&lt;p&gt;
For instance when it comes to generating getters and setters, Lombok makes them visible at compile time, making it possible for client code to use them without them appearing in the Java Bean class. 
&lt;br&gt;
Using bytecode manipulation to generate getters and setters, they become invisible to the compiler and cannot be used by another class, except using runtime reflection, which may be fine for some use cases (hibernate, etc) but not for most of them.
&lt;/p&gt;
&lt;p&gt;
&lt;b&gt;AST Transformation&lt;/b&gt;
&lt;/p&gt;
&lt;p&gt;
More information on Lombok&apos;s internal is availanle there: &lt;a href=&quot;https://www.ibm.com/developerworks/library/j-lombok/&quot;&gt;Custom AST transformations with Project Lombok&lt;/a&gt;.
&lt;/p&gt;

&lt;a name=&quot;sec315&quot;&gt;&lt;/a&gt;
&lt;h4&gt;3.1.5 Just a note on concerns&lt;/h4&gt;

&lt;p&gt;
I sometime hear (... read) arguments online against the use of Lombok. Most of the time, people against Lombok complain about the &lt;i&gt;magic&lt;/i&gt; added by Lombok.
&lt;/p&gt;
&lt;p&gt;
It is true that Lombok adds a lot of &lt;i&gt;magic&lt;/i&gt; to the application. But that magic is related to boilerplate code with no added value and easy to debug and understand in case of any doubt. In addition, it is very well recognized by most common IDEs such as eclipse and IDEA using well known or even official plugins.
&lt;/p&gt;

&lt;a name=&quot;sec32&quot;&gt;&lt;/a&gt;
&lt;h3&gt;3.2 Java agents and the linkage problem&lt;/h3&gt;

&lt;p&gt;
Javassist cannot modify a class after it has been loaded by a classloader ... as far as this classloader is concerned. 
&lt;br&gt;
Whenever one tries to modify a class already loaded by the referenced classloader, that attempt to call &lt;code&gt;pool.makeClass( ... )&lt;/code&gt; will fail and complain that class is &lt;i&gt;frozen&lt;/i&gt; (i.e. already created via &lt;code&gt;toClass()&lt;/code&gt;.
&lt;br&gt;
Being able to do that would require to &lt;i&gt;unload&lt;/i&gt; the class first from the reference Classloader.
&lt;/p&gt;
&lt;p&gt;
The problem here is that one cannot unload a single class from a ClassLoader. A class may be unloaded if it and its ClassLoader became unreachable but since every class refers to its loader that implies that all classes loaded by this loader must have to become unreachable too.
&lt;br&gt;
Of course one can (re-)create the class using a different ClassLoader but that would require to make the whole program use that new Classloader and this becomes fairly complicated.
&lt;br&gt;
At the end of the day, that would well require reloading the whole application and initializing everything all over again. This makes no sense.
&lt;/p&gt;
&lt;p&gt;
Let&apos;s just accept here that a class cannot be changed by Javassist once it has been already loaded by the Classloader.
&lt;/p&gt;

&lt;a name=&quot;sec321&quot;&gt;&lt;/a&gt;
&lt;h4&gt;3.2.1 Overcoming the Linkage problem with Java Agents&lt;/h4&gt;

&lt;p&gt;
The only (easy) way to overcome this problem is to change the class implementation using bytecode manipulation before the class is loaded by any Classloader. And happily, as often in the Java World, the JVM provides a mechanism for this, the JPLIS - &lt;i&gt;Java Programming Language Instrumentation Services&lt;/i&gt; - and the concept of &lt;i&gt;Java Agent&lt;/i&gt;.
&lt;/p&gt;
&lt;p&gt;
In its essence, a Java agent is a regular Java class which follows a set of strict conventions. The agent class must implement a &lt;code&gt;public static void premain(String agentArgs, Instrumentation inst)&lt;/code&gt; method which becomes an agent entry point (similar to the main method for regular Java applications).
&lt;/p&gt;
&lt;p&gt;
Once the Java Virtual Machine (JVM) has initialized, each such &lt;code&gt;premain(String agentArgs, Instrumentation inst)&lt;/code&gt; method of every agent will be called in the order the agents were specified on JVM start. When this initialization step is done, the real Java application main method will be called.
&lt;/p&gt;
&lt;p&gt;
The instrumentation capabilities of Java agents are truly unlimited. Most noticeable one is the ability to redefine classes at run-time. The redefinition may change method bodies, the constant pool and attributes. The redefinition must not add, remove or rename fields or methods, change the signatures of methods, or change inheritance.
&lt;/p&gt;
&lt;p&gt;
Please notice that re-transformed or redefined class bytecode is not checked, verified and installed just after the transformations or redefinitions have been applied. If the resulting bytecode is erroneous or not correct, the exception will be thrown and that may crash JVM completely.
&lt;/p&gt;


&lt;a name=&quot;sec322&quot;&gt;&lt;/a&gt;
&lt;h4&gt;3.2.2 ClassFileTransformer&lt;/h4&gt;

&lt;p&gt;
A Java agent &lt;code&gt;premain&lt;/code&gt; method takes the Instrumentation entry point - class &lt;code&gt;java.lang.instrument.Instrumentation&lt;/code&gt; - as argument. 
&lt;/p&gt;
&lt;p&gt;
The Instrumentation entry point provides several commodity methods to check the possibilities of the JVM but the most important API of the &lt;code&gt;java.lang.instrument.Instrumentation&lt;/code&gt; class is the method &lt;code&gt;void addTransformer(ClassFileTransformer transformer);&lt;/code&gt; that enable the developer to register several &lt;code&gt;java.lang.instrument.ClassFileTransformer&lt;/code&gt;.
&lt;/p&gt;
&lt;p&gt;
The &lt;code&gt;java.lang.instrument.ClassFileTransformer&lt;/code&gt; interface defines one single method &lt;code&gt;byte[] transform(...)&lt;/code&gt; that is responsible to apply transformations (as far as complete rewriting if required) the java classes being loaded by the JVM.
&lt;br&gt;
The &lt;code&gt;transform(...)&lt;/code&gt; method is called for each and every class being loaded by a classloader. Both the class being loaded and the classloader actually loading it as well as other information are given in argument.
&lt;/p&gt;
&lt;p&gt;
The &lt;code&gt;transform(...)&lt;/code&gt; method is the ideal place where bytecode manipulation libraries can be used to modify classes just before they are loaded by the classloader.
&lt;/p&gt;


&lt;div class=&quot;centering&quot;&gt;
&lt;a href=&quot;https://www.niceideas.ch/roller2/badtrash/mediaresource/62b1c423-2028-4ef3-ab25-37ac8bbaf7ab&quot;&gt;
&lt;img class=&quot;centered&quot; style=&quot;width: 450px;&quot; alt=&quot;Java Agent Behaviour&quot; src=&quot;https://www.niceideas.ch/roller2/badtrash/mediaresource/62b1c423-2028-4ef3-ab25-37ac8bbaf7ab&quot; /&gt;
&lt;/a&gt;&lt;br&gt;
&lt;div class=&quot;centered&quot;&gt;
(Source : &lt;a href=&quot;http://www.barcelonajug.org/2015/04/java-agents.html&quot;&gt;http://www.barcelonajug.org/2015/04/java-agents.html&lt;/a&gt;)
&lt;/div&gt;
&lt;/div&gt;
&lt;br&gt;



&lt;a name=&quot;sec323&quot;&gt;&lt;/a&gt;
&lt;h4&gt;3.2.3 Caution&lt;/h4&gt;

&lt;p&gt;
As a sidenote, the Java agent class may also have a &lt;code&gt;public static void agentmain(String agentArgs, Instrumentation inst)&lt;/code&gt;  method which is used when the agent is started after JVM startup.
&lt;/p&gt;
&lt;p&gt;
A common practice when developing agents is to implement both the &lt;code&gt;agentmain&lt;/code&gt; and &lt;code&gt;premain&lt;/code&gt; methods and delegate one to the other. See &lt;a href=&quot;#sec431&quot;&gt;implementation of Java Agent&lt;/a&gt; of BCG below.
&lt;/p&gt;


&lt;a name=&quot;sec324&quot;&gt;&lt;/a&gt;
&lt;h4&gt;3.2.4 Simple Example&lt;/h4&gt;

&lt;pre&gt;
&lt;b&gt;package&lt;/b&gt; ch.niceideas.common.agent;

&lt;b&gt;import&lt;/b&gt; java.lang.instrument.ClassFileTransformer;
&lt;b&gt;import&lt;/b&gt; java.lang.instrument.IllegalClassFormatException;
&lt;b&gt;import&lt;/b&gt; java.lang.instrument.Instrumentation;
&lt;b&gt;import&lt;/b&gt; java.security.ProtectionDomain;

&lt;b&gt;public class&lt;/b&gt; ClassLoadingLoggingAgent {

    &lt;b&gt;public static void&lt;/b&gt; premain(String agentArgument, Instrumentation instrumentation){     
        System.out.println(&lt;span style=&quot;color: blue;&quot;&gt;&quot;Hello, Agent [ &quot;&lt;/span&gt; + agentArgument + &lt;span style=&quot;color: blue;&quot;&gt;&quot; ]&quot;&lt;/span&gt;);

        instrumentation.addTransformer (&lt;b&gt;new&lt;/b&gt; ClassFileTransformer() {

            @Override
            &lt;b&gt;public byte&lt;/b&gt;[] transform(
                    ClassLoader loader, 
                    String className, 
                    Class&amp;lt;?&gt; classBeingRedefined, 
                    ProtectionDomain protectionDomain, 
                    &lt;b&gt;byte&lt;/b&gt;[] classfileBuffer) &lt;b&gt;throws&lt;/b&gt; IllegalClassFormatException {

                &lt;span style=&quot;color: green;&quot;&gt;// Transform is called just before class loading occurs :-)&lt;/span&gt;
                System.out.println(&lt;span style=&quot;color: blue;&quot;&gt;&quot;Class being loaded : &quot;&lt;/span&gt; + className);

                &lt;span style=&quot;color: green;&quot;&gt;// No transformation ...&lt;/span&gt;
                &lt;b&gt;return&lt;/b&gt; classfileBuffer;
            }
        });
    }
}
&lt;/pre&gt;

&lt;p&gt;
Let&apos;s now see how to invoke a simple program using this simple agent.
&lt;/p&gt;


&lt;a name=&quot;sec325&quot;&gt;&lt;/a&gt;
&lt;h4&gt;3.2.5 Invoking the Agent&lt;/h4&gt;

&lt;p&gt;
When running from the command line, the Java agent could be passed to JVM instance using &lt;code&gt;-javaagent&lt;/code&gt; argument which has following semantic &lt;code&gt;-javaagent:&amp;lt;path-to-jar&amp;gt;[=options]&lt;/code&gt;.
&lt;/p&gt;
&lt;p&gt;
A java agent needs to be packaged in a jar file and that jar file needs to have a specific and proper &lt;code&gt;MANIFEST.MF&lt;/code&gt; file indicating the class containing the &lt;code&gt;premain&lt;/code&gt; method.
&lt;/p&gt;
&lt;p&gt;
A proper manifest file for the agent above should be packages within the jar archive containing the agent classes under &lt;code&gt;META-INF/MANIFEST.MF&lt;/code&gt; and would be as follows:
&lt;/p&gt;

&lt;pre&gt;
Manifest-Version: 1.0
Premain-Class: ch.niceideas.common.agent.ClassLoadingLoggingAgent
&lt;/pre&gt;

&lt;p&gt;
Now let&apos;s imagine we invoke our agent on a simple program defined as follows:
&lt;/p&gt;


&lt;pre&gt;
&lt;b&gt;package&lt;/b&gt; ch.niceideas.common.enhancer;

&lt;b&gt;public class&lt;/b&gt; TestMain {

    &lt;b&gt;public static void&lt;/b&gt; main (String args[]) {
        System.out.println (&lt;span style=&quot;color: blue;&quot;&gt;&quot;Program Main&quot;&lt;/span&gt;);
    }
}
&lt;/pre&gt;

&lt;p&gt;
Sample result on this simple program is as follows:
&lt;/p&gt;

&lt;pre&gt;
badtrash@badbook:/data/work/niceideas-commons/target/test-classes$ &lt;span style=&quot;color: DarkBlue;&quot;&gt;java&lt;/span&gt; \
    &lt;span style=&quot;color: DarkBlue;&quot;&gt;-javaagent:&lt;/span&gt;/home/badtrash/ClassLoadingLoggingAgent.jar&lt;span style=&quot;color: DarkRed;&quot;&gt;=007&lt;/span&gt; \
    ch.niceideas.common.enhancer.TestMain

Hello, Agent [ 007 ]
Class being loaded : java/lang/invoke/MethodHandleImpl
Class being loaded : java/lang/invoke/MethodHandleImpl$1
Class being loaded : java/lang/invoke/MethodHandleImpl$2
Class being loaded : java/util/function/Function
Class being loaded : java/lang/invoke/MethodHandleImpl$3
Class being loaded : java/lang/invoke/MethodHandleImpl$4
Class being loaded : java/lang/ClassValue
Class being loaded : java/lang/ClassValue$Entry
Class being loaded : java/lang/ClassValue$Identity
Class being loaded : java/lang/ClassValue$Version
Class being loaded : java/lang/invoke/MemberName$Factory
Class being loaded : java/lang/invoke/MethodHandleStatics
Class being loaded : java/lang/invoke/MethodHandleStatics$1
Class being loaded : sun/launcher/LauncherHelper
Class being loaded : java/util/concurrent/ConcurrentHashMap$ForwardingNode
Class being loaded : sun/misc/URLClassPath$FileLoader$1
Class being loaded : java/lang/Package
Class being loaded : java/io/FileInputStream$1
Class being loaded : ch/niceideas/common/enhancer/TestMain
Class being loaded : sun/launcher/LauncherHelper$FXHelper
Class being loaded : java/lang/Class$MethodArray
Class being loaded : java/lang/Void
Program Main
Class being loaded : java/lang/Shutdown
Class being loaded : java/lang/Shutdown$Lock
&lt;/pre&gt;


&lt;a name=&quot;sec326&quot;&gt;&lt;/a&gt;
&lt;h4&gt;3.2.6 Workaround&lt;/h4&gt;

&lt;p&gt;
As a sidenote, and to conclude this section, let&apos;s just mention that using a java agent to inject behaviour at runtime using bytecode manipulation is not always a requirement, it depends eventually on the use case.
&lt;br&gt;
A pretty common approach favored over java agents usage is the subclassing approach. It consists in defining a new class as a subclass of the class to be enhanced and injecting the new behaviour to that subclass instead.
&lt;br&gt;
This is a pretty straightforward approach and prevents the usage of a java agent since we don&apos;t care whether or not the initial class has already be loaded. Since we define a new class, the subclass, we&apos;re good to go no matter what happens with the initial class.
&lt;/p&gt;
&lt;p&gt;
I have given an example of this approach in my previous article as &lt;a href=&quot;https://www.niceideas.ch/roller2/badtrash/entry/bytecode-manipulation-with-javassist-for#sec41&quot;&gt;described here&lt;/a&gt;.
&lt;/p&gt;
&lt;p&gt;
In the case of boilerplate code generation such as done by Lombok, using an agent is pretty much the only way. The Value Objects or Java Beans enhanced this way can well be used later by the running program for ORM concerns or IoC concerns. These other frameworks, such as hibernate or spring, very often use the subclassing approach to inject their own behaviour. 
&lt;br&gt;
If a programmer attempts to use the subclass trick to inject his own behaviour and then use his class with hibernate for instance, his changes will likely be ignored by hibernate or spring that will generate their own subclass (using CGLIB or Javassist) that can conflict the developer&apos;s own subclass. In this case enhancing the class itself is a way simpler approach.
&lt;/p&gt;
&lt;p&gt;
Finally, using a java agent is a convenient way to avoid situations where the developer attempts to enhance a class that has already been loaded by the classloader. But that is not necessarily always required and the developer can well choose to implement his own control over the application lifecycle to ensure he has the chance to modify classes before the application attempts to load them.
&lt;br&gt;
But that is impossible when using annotations of course and hence frameworks such as Lombok using annotations extensively have no other choice than using a java agent.
&lt;/p&gt;

&lt;a name=&quot;sec4&quot;&gt;&lt;/a&gt;
&lt;h2&gt;4. BCG: a simple approach for generating boilerplate code using Javassist&lt;/h2&gt;

&lt;p&gt;
Now back on the Javassist topic.
&lt;/p&gt;
&lt;p&gt;
The purpose of this article is to give a second example of a sound Javassist use case: the generation of boilerplate code using bytecode manipulation, just as project Lombok is doing.
&lt;br&gt;
In fact, I will present here the BCG tool that mimic Lombok and re-implement two features of the Lombok feature set.
&lt;/p&gt;
&lt;p&gt;
I am presenting here the few dozen lines of code on the BCG tool - BCG for &lt;i&gt;Boilerplate Code Generator&lt;/i&gt;. 
&lt;br&gt;
BCG is a simple tool that uses Javassist and implement a Java agent to key Lombok features:
&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;code&gt;toString()&lt;/code&gt; method generation&lt;/li&gt;
&lt;li&gt;property getters and setters generation&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;
Note that BCG is not a production tool or anything like it, it is really just a Javassist example and intended to demonstrate how straightforward, simple and efficient it would be to re-implement Lombok features using Javassist ... Should one want to do that, which is not likely since Lombok is working so cool and so easily extendable.
&lt;/p&gt;
&lt;p&gt;
As mentioned above, we will only be mimicking project Lombok here using bytecode manipulation. We are not implementing these features the same way Lombok is doing. Lombok is working at compile-time using AST Transformation. We will be working at runtime using bytecode manipulation.
&lt;/p&gt;


&lt;a name=&quot;sec41&quot;&gt;&lt;/a&gt;
&lt;h3&gt;4.1 Principle &lt;/h3&gt;

&lt;p&gt;
We want to be able to implement &lt;i&gt;transformers&lt;/i&gt; that take care of performing one specific modification to target classes and activated by the presence of one specific annotation on these classes.
&lt;/p&gt;
&lt;p&gt;
The key idea is to implement a &lt;i&gt;Java Agent&lt;/i&gt; that analyze each and every class just before is loaded by the classloader and verifies if this class needs to be transformed.
&lt;br&gt;
We want to implement &lt;i&gt;Transformers&lt;/i&gt; that recognize classes declaring a specific annotation and proceed with the transformation of these classes. 
&lt;br&gt;
We want the system to be easily extendable with new transformers.
&lt;/p&gt;


&lt;a name=&quot;sec42&quot;&gt;&lt;/a&gt;
&lt;h3&gt;4.2 Design &lt;/h3&gt;

&lt;p&gt;
The design of BCG is as follows:
&lt;/p&gt;

&lt;div class=&quot;centering&quot;&gt;
&lt;a href=&quot;https://www.niceideas.ch/roller2/badtrash/mediaresource/928b7d05-c842-400b-a285-297b795c5e4b&quot;&gt;
&lt;img class=&quot;centered&quot; style=&quot;width: 600px;&quot; alt=&quot;Boilerplate code generator design&quot; src=&quot;https://www.niceideas.ch/roller2/badtrash/mediaresource/928b7d05-c842-400b-a285-297b795c5e4b&quot; /&gt;
&lt;/a&gt;
&lt;/div&gt;
&lt;br&gt;

&lt;p&gt;
Principal components are as follows:
&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;b&gt;&lt;code&gt;EnhancerAgent&lt;/code&gt;&lt;/b&gt; : This is a JVM Agent that implements classes transformation from recognized annotations.
&lt;br&gt;
The EnhancerAgent is called before the application starts and registers a &lt;code&gt;java.lang.instrument.ClassFileTransformer&lt;/code&gt; that enhances classes declaring specific annotations before they are loaded by classloader(s).
&lt;br&gt;
The &lt;code&gt;java.lang.instrument.ClassFileTransformer&lt;/code&gt; here is a simple anonymous adapter.
&lt;/li&gt;
&lt;li&gt;
&lt;b&gt;&lt;code&gt;ClassTransformer&lt;/code&gt;&lt;/b&gt; : This is an interface implemented by actual Class Transformers. A Class Transformer transforms Java classes declaring the recognized
annotation(s) using Javassist.
&lt;/li&gt;
&lt;li&gt;
&lt;b&gt;&lt;code&gt;AbstractTransformer&lt;/code&gt;&lt;/b&gt; : This is the base class for all Transformers. It provides commodity routines for ClassTransformers and simplifies registration API.
&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;
Then all actual transformers extend &lt;code&gt;AbstractTransformer&lt;/code&gt; and simply declare the annotation they recognize.
&lt;/p&gt;


&lt;a name=&quot;sec43&quot;&gt;&lt;/a&gt;
&lt;h3&gt;4.3 Implementation&lt;/h3&gt;

&lt;p&gt;
The source code of all classes and interfaces from the design above is given below.
&lt;/p&gt;
&lt;p&gt;
(In all snippets of code from now on, &lt;code&gt;&lt;span style=&quot;color: DarkRed&quot;&gt;I will be coloring relevant Javassist API calls in dark red&lt;/span&gt;&lt;/code&gt;)
&lt;/p&gt;

&lt;a name=&quot;sec431&quot;&gt;&lt;/a&gt;
&lt;h4&gt;4.3.1 The code of the Agent&lt;/h4&gt;

&lt;p&gt;
&lt;b&gt;[Class &lt;code&gt;EnhancerAgent&lt;/code&gt;]&lt;/b&gt;
&lt;/p&gt;

&lt;pre&gt;
&lt;b&gt;package&lt;/b&gt; ch.niceideas.common.enhancer;

&lt;b&gt;import&lt;/b&gt; ch.niceideas.common.enhancer.impls.CountInstanceTransformer;
&lt;b&gt;import&lt;/b&gt; ch.niceideas.common.enhancer.impls.DataTransformer;
&lt;b&gt;import&lt;/b&gt; ch.niceideas.common.enhancer.impls.ToStringTransformer;
&lt;b&gt;import&lt;/b&gt; &lt;span style=&quot;color: DarkRed&quot;&gt;javassist.CannotCompileException&lt;/span&gt;;
&lt;b&gt;import&lt;/b&gt; &lt;span style=&quot;color: DarkRed&quot;&gt;javassist.ClassPool&lt;/span&gt;;
&lt;b&gt;import&lt;/b&gt; &lt;span style=&quot;color: DarkRed&quot;&gt;javassist.CtClass&lt;/span&gt;;

&lt;b&gt;import&lt;/b&gt; java.io.IOException;
&lt;b&gt;import&lt;/b&gt; java.lang.annotation.Annotation;
&lt;b&gt;import&lt;/b&gt; java.lang.instrument.ClassFileTransformer;
&lt;b&gt;import&lt;/b&gt; java.lang.instrument.IllegalClassFormatException;
&lt;b&gt;import&lt;/b&gt; java.lang.instrument.Instrumentation;
&lt;b&gt;import&lt;/b&gt; java.security.ProtectionDomain;
&lt;b&gt;import&lt;/b&gt; java.util.ArrayList;
&lt;b&gt;import&lt;/b&gt; java.util.List;

&lt;span style=&quot;color: green;&quot;&gt;/**
 * This is a JVM Agent that implements classes transformation from recognized
 * annotations.
 * &amp;lt;p /&amp;gt;
 *
 * The EnhancerAgent is called before the application starts and registers a
 * &amp;lt;code&amp;gt;java.lang.instrument.ClassFileTransformer&amp;lt;/code&amp;gt; that enhances
 * classes declaring specific annotations before they are loaded
 * by classloader(s).
 * &amp;lt;p /&gt;
 *
 * The &amp;lt;code&amp;gt;java.lang.instrument.ClassFileTransformer&amp;lt;/code&amp;gt; here is a simple
 * anonymous adapter.
 */&lt;/span&gt;
&lt;b&gt;public class&lt;/b&gt; EnhancerAgent {

    &lt;b&gt;private static&lt;/b&gt; ClassTransformer[] transformers = &lt;b&gt;null&lt;/b&gt;;

    &lt;span style=&quot;color: green;&quot;&gt;// for now I don&apos;t have any better way than declaring all transformers here&lt;/span&gt;
    &lt;b&gt;static&lt;/b&gt; {
        transformers = &lt;b&gt;new&lt;/b&gt; ClassTransformer[] {
                &lt;b&gt;new&lt;/b&gt; CountInstanceTransformer(),
                &lt;b&gt;new&lt;/b&gt; ToStringTransformer(),
                &lt;b&gt;new&lt;/b&gt; DataTransformer()
        };
    }

    &lt;span style=&quot;color: green;&quot;&gt;// Java Agent API&lt;/span&gt;
    &lt;b&gt;public static void&lt;/b&gt; premain(String agentArgs, Instrumentation inst) {
        agentmain (agentArgs, inst);
    }

    &lt;span style=&quot;color: green;&quot;&gt;// API used when agent invoked after JVM Startup&lt;/span&gt;
    &lt;b&gt;public static void&lt;/b&gt; agentmain(String agentArgs, Instrumentation inst) {

        inst.addTransformer(&lt;b&gt;new&lt;/b&gt; ClassFileTransformer() {

            @Override
            &lt;b&gt;public byte&lt;/b&gt;[] transform (
                    ClassLoader loader,
                    String className,
                    Class&amp;lt;?&gt; classBeingRedefined,
                    ProtectionDomain protectionDomain,
                    &lt;b&gt;byte&lt;/b&gt;[] classfileBuffer)
                    &lt;b&gt;throws&lt;/b&gt; IllegalClassFormatException {

                &lt;span style=&quot;color: green;&quot;&gt;// Can return null if no transformation is performed&lt;/span&gt;
                &lt;b&gt;byte&lt;/b&gt;[] transformedClass = &lt;b&gt;null&lt;/b&gt;;

                &lt;span style=&quot;color: DarkRed&quot;&gt;CtClass&lt;/span&gt; cl = &lt;b&gt;null&lt;/b&gt;;
                &lt;span style=&quot;color: DarkRed&quot;&gt;ClassPool&lt;/span&gt; pool = &lt;span style=&quot;color: DarkRed&quot;&gt;ClassPool.getDefault&lt;/span&gt;();
                &lt;b&gt;try&lt;/b&gt; {
                    cl = pool.&lt;span style=&quot;color: DarkRed&quot;&gt;makeClass&lt;/span&gt;(&lt;b&gt;new&lt;/b&gt; java.io.ByteArrayInputStream(classfileBuffer));

                    &lt;b&gt;for&lt;/b&gt; (ClassTransformer transformer : transformers) {

                        &lt;b&gt;if&lt;/b&gt; (transformer.accepts (cl)) {
                            transformer.transform (cl);
                            System.out.println (&lt;span style=&quot;color: blue;&quot;&gt;&quot;Transformed class &quot;&lt;/span&gt; + cl.getName()
                                    + &lt;span style=&quot;color: blue;&quot;&gt;&quot; with &quot;&lt;/span&gt; + transformer.getClass().getSimpleName());
                        }
                    }

                    &lt;span style=&quot;color: green;&quot;&gt;// Generate changed bytecode&lt;/span&gt;
                    transformedClass = cl.&lt;span style=&quot;color: DarkRed&quot;&gt;toBytecode&lt;/span&gt;();

                } &lt;b&gt;catch&lt;/b&gt; (IOException | &lt;span style=&quot;color: DarkRed&quot;&gt;CannotCompileException&lt;/span&gt; e) {
                    e.printStackTrace();

                } &lt;b&gt;finally&lt;/b&gt; {
                    &lt;b&gt;if&lt;/b&gt; (cl != &lt;b&gt;null&lt;/b&gt;) {
                        cl.&lt;span style=&quot;color: DarkRed&quot;&gt;detach&lt;/span&gt;();
                    }
                }

                &lt;b&gt;return&lt;/b&gt; transformedClass;
            }
        });
    }
}
&lt;/pre&gt;

&lt;a name=&quot;sec432&quot;&gt;&lt;/a&gt;
&lt;h4&gt;4.3.2 Interface ClassTransformer&lt;/h4&gt;

&lt;p&gt;
Transformers implement this interface:
&lt;/p&gt;
&lt;p&gt;
&lt;b&gt;[Class &lt;code&gt;ClassTransformer&lt;/code&gt;]&lt;/b&gt;
&lt;/p&gt;

&lt;pre&gt;
&lt;b&gt;package&lt;/b&gt; ch.niceideas.common.enhancer;

&lt;b&gt;import&lt;/b&gt; &lt;span style=&quot;color: DarkRed&quot;&gt;javassist.CtClass&lt;/span&gt;;

&lt;span style=&quot;color: green;&quot;&gt;/**
 * A class Transformer transforms Java classes declaring the recognized
 * annotation(s) using Javassist.
 */&lt;/span&gt;
&lt;b&gt;public interface&lt;/b&gt; ClassTransformer {

    &lt;span style=&quot;color: green;&quot;&gt;/**
     * Used by the EnhancerAgent to know whether this class accepts the supported anotation
     *
     * @param cl the class to test
     * @return true if the passed annotation is accepted
     */&lt;/span&gt;
    &lt;b&gt;boolean&lt;/b&gt; accepts(&lt;span style=&quot;color: DarkRed&quot;&gt;CtClass&lt;/span&gt; cl);

    &lt;span style=&quot;color: green;&quot;&gt;/**
     * Proceed with the transformation of the javassist loaded class given as argument
     *
     * @param cl the javassist loaded class to be transformed
     */&lt;/span&gt;
    &lt;b&gt;void&lt;/b&gt; transform(&lt;span style=&quot;color: DarkRed&quot;&gt;CtClass&lt;/span&gt; cl);

}
&lt;/pre&gt;

&lt;a name=&quot;sec433&quot;&gt;&lt;/a&gt;
&lt;h4&gt;4.3.3 Common Abstraction&lt;/h4&gt;

&lt;p&gt;
And an abstract class provides some binding commodities to transformers
&lt;/p&gt;
&lt;p&gt;
&lt;b&gt;[Class &lt;code&gt;AbstractTransformer&lt;/code&gt;]&lt;/b&gt;
&lt;/p&gt;

&lt;pre&gt;
&lt;b&gt;package&lt;/b&gt; ch.niceideas.common.enhancer.impls;

&lt;b&gt;import&lt;/b&gt; ch.niceideas.common.enhancer.ClassTransformer;
&lt;b&gt;import&lt;/b&gt; &lt;span style=&quot;color: DarkRed&quot;&gt;javassist.CtClass&lt;/span&gt;;

&lt;b&gt;import&lt;/b&gt; java.lang.annotation.Annotation;

&lt;span style=&quot;color: green;&quot;&gt;/**
 * Base class for ClassTransformers.
 * &amp;lt;br /&amp;gt;
 * Provides commodity routines for ClassTransformers and simplifies registration API.
 */&lt;/span&gt;
&lt;b&gt;public abstract class&lt;/b&gt; AbstractTransformer &lt;b&gt;implements&lt;/b&gt; ClassTransformer {

    @Override
    &lt;b&gt;public final boolean&lt;/b&gt; accepts(&lt;span style=&quot;color: DarkRed&quot;&gt;CtClass&lt;/span&gt; cl) {
        &lt;b&gt;return&lt;/b&gt; cl.&lt;span style=&quot;color: DarkRed&quot;&gt;hasAnnotation&lt;/span&gt;(getAnnotationClass());
    }

    &lt;span style=&quot;color: green;&quot;&gt;/**
     * Classes that wants to be transformed by this transformer needs to declare
     * this annotation.
     *
     * @return the type of the annotation accepted by this transformer.
     */&lt;/span&gt;
    &lt;b&gt;protected abstract&lt;/b&gt; Class&amp;lt;? &lt;b&gt;extends&lt;/b&gt; Annotation&amp;gt; getAnnotationClass();

    @Override
    &lt;b&gt;public abstract void&lt;/b&gt; transform(&lt;span style=&quot;color: DarkRed&quot;&gt;CtClass&lt;/span&gt; cl);
}

&lt;/pre&gt;


&lt;a name=&quot;sec434&quot;&gt;&lt;/a&gt;
&lt;h4&gt;4.3.4 The set of Class Transformers&lt;/h4&gt;

&lt;p&gt;
A first Class Transformer : outputs the count of instances of classes declaring the &lt;code&gt;@CountInstance&lt;/code&gt; annotation.
&lt;/p&gt;
&lt;p&gt;
&lt;b&gt;[Class &lt;code&gt;CountInstanceTransformer&lt;/code&gt;]&lt;/b&gt;
&lt;/p&gt;

&lt;pre&gt;
&lt;b&gt;package&lt;/b&gt; ch.niceideas.common.enhancer.impls;

&lt;b&gt;import&lt;/b&gt; ch.niceideas.common.enhancer.ClassTransformer;
&lt;b&gt;import&lt;/b&gt; ch.niceideas.common.enhancer.annotations.CountInstance;
&lt;b&gt;import&lt;/b&gt; &lt;span style=&quot;color: DarkRed&quot;&gt;javassist.CannotCompileException&lt;/span&gt;;
&lt;b&gt;import&lt;/b&gt; &lt;span style=&quot;color: DarkRed&quot;&gt;javassist.CtBehavior&lt;/span&gt;;
&lt;b&gt;import&lt;/b&gt; &lt;span style=&quot;color: DarkRed&quot;&gt;javassist.CtClass&lt;/span&gt;;
&lt;b&gt;import&lt;/b&gt; &lt;span style=&quot;color: DarkRed&quot;&gt;javassist.CtField&lt;/span&gt;;

&lt;b&gt;import&lt;/b&gt; java.lang.annotation.Annotation;

&lt;span style=&quot;color: green;&quot;&gt;/**
 * This transformer accepts classe declaring the &quot;@CountInstance&quot; annotation.
 * &lt;br&gt;
 * It enhances the class with an instanceCounter and outputs the value of ths
 * instanceCounter everytime an instance is built.
 */&lt;/span&gt;
&lt;b&gt;public class&lt;/b&gt; CountInstanceTransformer &lt;b&gt;extends&lt;/b&gt; AbstractTransformer 
        &lt;b&gt;implements&lt;/b&gt; ClassTransformer {

    @Override
    &lt;b&gt;protected&lt;/b&gt; Class&amp;lt;? &lt;b&gt;extends&lt;/b&gt; Annotation&amp;gt; getAnnotationClass() {
        &lt;b&gt;return&lt;/b&gt; CountInstance.&lt;b&gt;class&lt;/b&gt;;
    }

    @Override
    &lt;b&gt;public void&lt;/b&gt; transform(&lt;span style=&quot;color: DarkRed&quot;&gt;CtClass&lt;/span&gt; cl) {
        &lt;b&gt;try&lt;/b&gt; {
            &lt;b&gt;if&lt;/b&gt; (!cl.&lt;span style=&quot;color: DarkRed&quot;&gt;isInterface&lt;/span&gt;()) {

                &lt;span style=&quot;color: green;&quot;&gt;// Add a static field in the class&lt;/span&gt;
                &lt;span style=&quot;color: DarkRed&quot;&gt;CtField&lt;/span&gt; field = &lt;span style=&quot;color: DarkRed&quot;&gt;CtField.make&lt;/span&gt;(&lt;span style=&quot;color: blue;&quot;&gt;&quot;private static long _instanceCount;&quot;&lt;/span&gt;, cl);
                cl.&lt;span style=&quot;color: DarkRed&quot;&gt;addField&lt;/span&gt;(field);

                &lt;span style=&quot;color: DarkRed&quot;&gt;CtBehavior&lt;/span&gt;[] constructors = cl.&lt;span style=&quot;color: DarkRed&quot;&gt;getDeclaredConstructors&lt;/span&gt;();
                &lt;b&gt;for&lt;/b&gt; (&lt;b&gt;int&lt;/b&gt; i = 0; i &amp;lt; constructors.length; i++) {

                    &lt;span style=&quot;color: green;&quot;&gt;// Increment counter and output it&lt;/span&gt;
                    constructors[i].&lt;span style=&quot;color: DarkRed&quot;&gt;insertAfter&lt;/span&gt;(&lt;span style=&quot;color: blue;&quot;&gt;&quot;_instanceCount++;&quot;&lt;/span&gt;);
                    constructors[i].&lt;span style=&quot;color: DarkRed&quot;&gt;insertAfter&lt;/span&gt;(&lt;span style=&quot;color: blue;&quot;&gt;&quot;System.out.println(\&quot;&quot;&lt;/span&gt;
                            + cl.&lt;span style=&quot;color: DarkRed&quot;&gt;getName&lt;/span&gt;() + &lt;span style=&quot;color: blue;&quot;&gt;&quot; : \&quot; + _instanceCount);&quot;&lt;/span&gt;);
                }
            }

        } &lt;b&gt;catch&lt;/b&gt; (&lt;span style=&quot;color: DarkRed&quot;&gt;CannotCompileException&lt;/span&gt; e) {
            e.printStackTrace();
            &lt;b&gt;throw new&lt;/b&gt; RuntimeException (e);
        }
    }
}
&lt;/pre&gt;

&lt;p&gt;
The &lt;code&gt;CountInstanceTransformer&lt;/code&gt; accepts classes declaring the &lt;code&gt;CountInstance&lt;/code&gt; annotation :
&lt;/p&gt;

&lt;pre&gt;
&lt;b&gt;package&lt;/b&gt; ch.niceideas.common.enhancer.annotations;

&lt;span style=&quot;color: green;&quot;&gt;/**
 * Classes declaring this annotation will have an instancecounter which value is
 * output everytime an instance is constructed
 */&lt;/span&gt;
&lt;b&gt;public @interface&lt;/b&gt; CountInstance {
}

&lt;/pre&gt;

&lt;p&gt;
Second Class Transformer: generates getters and setters for classes declaring the &lt;code&gt;@Data&lt;/code&gt; annotation.
&lt;/p&gt;
&lt;p&gt;
&lt;b&gt;[Class &lt;code&gt;DataTransformer&lt;/code&gt;]&lt;/b&gt;
&lt;/p&gt;


&lt;pre&gt;
&lt;b&gt;package&lt;/b&gt; ch.niceideas.common.enhancer.impls;

&lt;b&gt;import&lt;/b&gt; ch.niceideas.common.enhancer.ClassTransformer;
&lt;b&gt;import&lt;/b&gt; ch.niceideas.common.enhancer.annotations.Data;
&lt;b&gt;import&lt;/b&gt; &lt;span style=&quot;color: DarkRed&quot;&gt;javassist.*&lt;/span&gt;;

&lt;b&gt;import&lt;/b&gt; java.lang.annotation.Annotation;

&lt;span style=&quot;color: green;&quot;&gt;/**
 * This transformer accepts classes declaring the &quot;@Data&quot; annotation.
 * &amp;lt;br /&amp;gt;
 * It generates a getters and setters dynamically for every field of the class
 * if they do not already exist
 */&lt;/span&gt;
&lt;b&gt;public class&lt;/b&gt; DataTransformer &lt;b&gt;extends&lt;/b&gt; AbstractTransformer &lt;b&gt;implements&lt;/b&gt; ClassTransformer {

    @Override
    &lt;b&gt;protected&lt;/b&gt; Class&amp;lt;? &lt;b&gt;extends&lt;/b&gt; Annotation&amp;gt; getAnnotationClass() {
        &lt;b&gt;return&lt;/b&gt; Data.&lt;b&gt;class&lt;/b&gt;;
    }

    @Override
    &lt;b&gt;public void&lt;/b&gt; transform(&lt;span style=&quot;color: DarkRed&quot;&gt;CtClass&lt;/span&gt; cl) {
        &lt;b&gt;try&lt;/b&gt; {
            &lt;b&gt;if&lt;/b&gt; (!cl.&lt;span style=&quot;color: DarkRed&quot;&gt;isInterface&lt;/span&gt;()) {

                &lt;b&gt;for&lt;/b&gt; (&lt;span style=&quot;color: DarkRed&quot;&gt;CtField&lt;/span&gt; field : cl.&lt;span style=&quot;color: DarkRed&quot;&gt;getDeclaredFields&lt;/span&gt;()) {

                    String camelCaseField = field.getName().substring(0, 1).toUpperCase()
                            + field.getName().substring(1);

                    if (!hasMethod(&lt;span style=&quot;color: blue;&quot;&gt;&quot;get&quot;&lt;/span&gt; + camelCaseField, cl)) {
                        cl.&lt;span style=&quot;color: DarkRed&quot;&gt;addMethod&lt;/span&gt;(&lt;span style=&quot;color: DarkRed&quot;&gt;CtNewMethod.getter&lt;/span&gt;(&lt;span style=&quot;color: blue;&quot;&gt;&quot;get&quot;&lt;/span&gt; + camelCaseField, field));
                    }

                    if (!hasMethod(&lt;span style=&quot;color: blue;&quot;&gt;&quot;set&quot;&lt;/span&gt; + camelCaseField, cl)) {
                        cl.&lt;span style=&quot;color: DarkRed&quot;&gt;addMethod&lt;/span&gt;(&lt;span style=&quot;color: DarkRed&quot;&gt;CtNewMethod.setter&lt;/span&gt;(&lt;span style=&quot;color: blue;&quot;&gt;&quot;set&quot;&lt;/span&gt; + camelCaseField, field));
                    }
                }
            }

        } &lt;b&gt;catch&lt;/b&gt; (&lt;span style=&quot;color: DarkRed&quot;&gt;CannotCompileException&lt;/span&gt; e) {
            e.printStackTrace();
            &lt;b&gt;throw new&lt;/b&gt; RuntimeException(e);
        }
    }

    &lt;span style=&quot;color: green;&quot;&gt;/** javassist has unfortunately no hasMethod API */&lt;/span&gt;
    &lt;b&gt;private static boolean&lt;/b&gt; hasMethod (String methodName, &lt;span style=&quot;color: DarkRed&quot;&gt;CtClass&lt;/span&gt; cl) {
        &lt;b&gt;try&lt;/b&gt; {
            cl.&lt;span style=&quot;color: DarkRed&quot;&gt;getDeclaredMethod&lt;/span&gt;(methodName);
            &lt;b&gt;return true&lt;/b&gt;;
        } &lt;b&gt;catch&lt;/b&gt; (&lt;span style=&quot;color: DarkRed&quot;&gt;NotFoundException&lt;/span&gt; e) {
            &lt;b&gt;return false&lt;/b&gt;;
        }
    }
}
&lt;/pre&gt;

&lt;p&gt;
The &lt;code&gt;DataTransformer&lt;/code&gt; accepts classes declaring the &lt;code&gt;Data&lt;/code&gt; annotation :
&lt;/p&gt;

&lt;pre&gt;
&lt;b&gt;package&lt;/b&gt; ch.niceideas.common.enhancer.annotations;

&lt;span style=&quot;color: green;&quot;&gt;/**
 * Classes declaring this annotation will have getters and setters automatically
 * generated
 */&lt;/span&gt;
&lt;b&gt;public @interface&lt;/b&gt; Data {
}
&lt;/pre&gt;

&lt;p&gt;
Third Class Transformer : generates the &lt;code&gt;toString&lt;/code&gt; method for classes declaring the &lt;code&gt;@ToString&lt;/code&gt; annotation.
&lt;/p&gt;
&lt;p&gt;
&lt;b&gt;[Class &lt;code&gt;DataTransformer&lt;/code&gt;]&lt;/b&gt;
&lt;/p&gt;

&lt;pre&gt;
&lt;b&gt;package&lt;/b&gt; ch.niceideas.common.enhancer.impls;

&lt;b&gt;import&lt;/b&gt; ch.niceideas.common.enhancer.ClassTransformer;
&lt;b&gt;import&lt;/b&gt; ch.niceideas.common.enhancer.annotations.ToString;
&lt;b&gt;import&lt;/b&gt; &lt;span style=&quot;color: DarkRed&quot;&gt;javassist.*&lt;/span&gt;;

&lt;b&gt;import&lt;/b&gt; java.lang.annotation.Annotation;

&lt;span style=&quot;color: green;&quot;&gt;/**
 * This transformer accepts classes declaring the &quot;@ToString&quot; annotation.
 * &amp;lt;br /&amp;gt;
 * It generates a toString method dynamically. The toString method is generated using
 * bytecode manipulation and avoids reflection.
 */&lt;/span&gt;
&lt;b&gt;public class&lt;/b&gt; ToStringTransformer &lt;b&gt;extends&lt;/b&gt; AbstractTransformer &lt;b&gt;implements&lt;/b&gt; ClassTransformer {

    @Override
    &lt;b&gt;protected&lt;/b&gt; Class&amp;lt;? extends Annotation&amp;gt; getAnnotationClass() {
        &lt;b&gt;return&lt;/b&gt; ToString.&lt;b&gt;class&lt;/b&gt;;
    }

    @Override
    &lt;b&gt;public void&lt;/b&gt; transform(&lt;span style=&quot;color: DarkRed&quot;&gt;CtClass&lt;/span&gt; cl) {
        &lt;b&gt;try&lt;/b&gt; {
            &lt;b&gt;if&lt;/b&gt; (!cl.&lt;span style=&quot;color: DarkRed&quot;&gt;isInterface&lt;/span&gt;()) {

                StringBuilder bb = &lt;b&gt;new&lt;/b&gt; StringBuilder(&lt;span style=&quot;color: blue;&quot;&gt;&quot;{\n&quot;&lt;/span&gt;);
                bb.append(&lt;span style=&quot;color: blue;&quot;&gt;&quot;    StringBuilder sb = new StringBuilder(\&quot;&quot;&lt;/span&gt; 
                        + cl.getName() + &lt;span style=&quot;color: blue;&quot;&gt;&quot;\&quot;);\n&quot;&lt;/span&gt;);
                bb.append(&lt;span style=&quot;color: blue;&quot;&gt;&quot;    sb.append(\&quot;[\&quot;);\n&quot;&lt;/span&gt;);

                &lt;b&gt;for&lt;/b&gt; (&lt;span style=&quot;color: DarkRed&quot;&gt;CtField&lt;/span&gt; field : cl.&lt;span style=&quot;color: DarkRed&quot;&gt;getDeclaredFields&lt;/span&gt;()) {
                    field.&lt;span style=&quot;color: DarkRed&quot;&gt;setModifiers&lt;/span&gt;(Modifier.PUBLIC); &lt;span style=&quot;color: green;&quot;&gt;// hacky hack&lt;/span&gt;

                    bb.append(&lt;span style=&quot;color: blue;&quot;&gt;&quot;    sb.append(\&quot;&quot;&lt;/span&gt; + field.&lt;span style=&quot;color: DarkRed&quot;&gt;getName&lt;/span&gt;() + &lt;span style=&quot;color: blue;&quot;&gt;&quot;\&quot;);\n&quot;&lt;/span&gt;);
                    bb.append(&lt;span style=&quot;color: blue;&quot;&gt;&quot;    sb.append(\&quot;=\&quot;);\n&quot;&lt;/span&gt;);
                    bb.append(&lt;span style=&quot;color: blue;&quot;&gt;&quot;    sb.append(this.&quot;&lt;/span&gt; + field.&lt;span style=&quot;color: DarkRed&quot;&gt;getName&lt;/span&gt;() + &lt;span style=&quot;color: blue;&quot;&gt;&quot;);\n&quot;&lt;/span&gt;);
                    bb.append(&lt;span style=&quot;color: blue;&quot;&gt;&quot;    sb.append(\&quot; \&quot;);\n&quot;&lt;/span&gt;);
                }

                bb.append(&lt;span style=&quot;color: blue;&quot;&gt;&quot;    sb.append(\&quot;]\&quot;);\n&quot;&lt;/span&gt;);
                bb.append(&lt;span style=&quot;color: blue;&quot;&gt;&quot;    return sb.toString();\n&quot;&lt;/span&gt;);
                bb.append(&lt;span style=&quot;color: blue;&quot;&gt;&quot;}&quot;&lt;/span&gt;);

                &lt;b&gt;try&lt;/b&gt; {
                    &lt;span style=&quot;color: DarkRed&quot;&gt;CtMethod&lt;/span&gt; toStringMethod = cl.&lt;span style=&quot;color: DarkRed&quot;&gt;getDeclaredMethod&lt;/span&gt;(&lt;span style=&quot;color: blue;&quot;&gt;&quot;toString&quot;&lt;/span&gt;);
                    toStringMethod.&lt;span style=&quot;color: DarkRed&quot;&gt;setBody&lt;/span&gt;(bb.toString());

                } &lt;b&gt;catch&lt;/b&gt; (&lt;span style=&quot;color: DarkRed&quot;&gt;NotFoundException&lt;/span&gt; e) {

                    &lt;span style=&quot;color: DarkRed&quot;&gt;CtMethod&lt;/span&gt; newMethod = &lt;span style=&quot;color: DarkRed&quot;&gt;CtNewMethod.make&lt;/span&gt;(&lt;span style=&quot;color: blue;&quot;&gt;&quot;public String toString() \n&quot;&lt;/span&gt;
                            + bb.toString(), cl);
                    cl.&lt;span style=&quot;color: DarkRed&quot;&gt;addMethod&lt;/span&gt;(newMethod);
                }
            }

        } &lt;b&gt;catch&lt;/b&gt; (&lt;span style=&quot;color: DarkRed&quot;&gt;CannotCompileException&lt;/span&gt; e) {
            e.printStackTrace();
            &lt;b&gt;throw new&lt;/b&gt; RuntimeException (e);
        }
    }
}
&lt;/pre&gt;

&lt;p&gt;
The &lt;code&gt;ToStringTransformer&lt;/code&gt; accepts classes declaring the &lt;code&gt;ToString&lt;/code&gt; annotation :
&lt;/p&gt;

&lt;pre&gt;
&lt;b&gt;package&lt;/b&gt; ch.niceideas.common.enhancer.annotations;

&lt;span style=&quot;color: green;&quot;&gt;/**
 * Classes declaring this annotation will have a toString method generated
 * automagically
 */&lt;/span&gt;
&lt;b&gt;public @interface&lt;/b&gt; ToString {
}
&lt;/pre&gt;


&lt;a name=&quot;sec435&quot;&gt;&lt;/a&gt;
&lt;h4&gt;4.3.5 Test Class Example&lt;/h4&gt;

&lt;p&gt;
A test class for the &lt;code&gt;DataTransformer&lt;/code&gt; for instance, with the usage of a nice library to test agents: ElectronicArts AgentLoader.
&lt;/p&gt;
&lt;p&gt;
EA Agent Loader is a collection of utilities for java agent developers. It allows programmers to write and test their java agents using dynamic agent loading (without using the -javaagent jvm parameter).
&lt;/p&gt;

&lt;pre&gt;
&lt;b&gt;package&lt;/b&gt; ch.niceideas.common.enhancer;

&lt;b&gt;import&lt;/b&gt; ch.niceideas.common.enhancer.testData.TestData;
&lt;b&gt;import&lt;/b&gt; com.ea.agentloader.AgentLoader;
&lt;b&gt;import&lt;/b&gt; junit.framework.TestCase;
&lt;b&gt;import&lt;/b&gt; org.apache.log4j.Logger;
&lt;b&gt;import&lt;/b&gt; org.junit.Before;
&lt;b&gt;import&lt;/b&gt; org.junit.Test;

&lt;b&gt;import&lt;/b&gt; java.lang.reflect.Method;

&lt;b&gt;public class&lt;/b&gt; DataTest &lt;b&gt;extends&lt;/b&gt; TestCase{

    &lt;b&gt;private static final&lt;/b&gt; Logger logger = Logger.getLogger(DataTest.&lt;b&gt;class&lt;/b&gt;);

    @Before
    &lt;b&gt;public void&lt;/b&gt; setUp() &lt;b&gt;throws&lt;/b&gt; Exception {
        AgentLoader.loadAgentClass(EnhancerAgent.&lt;b&gt;class&lt;/b&gt;.getName(), &lt;span style=&quot;color: blue;&quot;&gt;&quot;&quot;&lt;/span&gt;);
    }

    @Test
    &lt;b&gt;public void&lt;/b&gt; testDataTransformer() &lt;b&gt;throws&lt;/b&gt; Exception {

        TestData testData = &lt;b&gt;new&lt;/b&gt; TestData();

        Method getI = TestData.&lt;b&gt;class&lt;/b&gt;.getDeclaredMethod(&lt;span style=&quot;color: blue;&quot;&gt;&quot;getI&quot;&lt;/span&gt;);
        assertEquals (0, getI.invoke(testData));

        Method getMyString = TestData.&lt;b&gt;class&lt;/b&gt;.getDeclaredMethod(&lt;span style=&quot;color: blue;&quot;&gt;&quot;getMyString&quot;&lt;/span&gt;);
        assertEquals (&lt;span style=&quot;color: blue;&quot;&gt;&quot;abc&quot;&lt;/span&gt;, getMyString.invoke(testData));

        Method getValue = TestData.&lt;b&gt;class&lt;/b&gt;.getDeclaredMethod(&lt;span style=&quot;color: blue;&quot;&gt;&quot;getValue&quot;&lt;/span&gt;);
        assertEquals (-1L, getValue.invoke(testData));

        Method setI = TestData.&lt;b&gt;class&lt;/b&gt;.getDeclaredMethod(&lt;span style=&quot;color: blue;&quot;&gt;&quot;setI&quot;&lt;/span&gt;, &lt;b&gt;int&lt;/b&gt;.&lt;b&gt;class&lt;/b&gt;);
        setI.invoke(testData, 9);
        assertEquals (9, getI.invoke(testData));

        Method setMyString = TestData.&lt;b&gt;class&lt;/b&gt;.getDeclaredMethod(&lt;span style=&quot;color: blue;&quot;&gt;&quot;setMyString&quot;&lt;/span&gt;, String.&lt;b&gt;class&lt;/b&gt;);
        setMyString.invoke(testData, &lt;span style=&quot;color: blue;&quot;&gt;&quot;xyz&quot;&lt;/span&gt;);
        assertEquals (&lt;span style=&quot;color: blue;&quot;&gt;&quot;xyz&quot;&lt;/span&gt;, getMyString.invoke(testData));

        Method setValue = TestData.&lt;b&gt;class&lt;/b&gt;.getDeclaredMethod(&lt;span style=&quot;color: blue;&quot;&gt;&quot;setValue&quot;&lt;/span&gt;, &lt;b&gt;long&lt;/b&gt;.&lt;b&gt;class&lt;/b&gt;);
        setValue.invoke(testData, 999L);
        assertEquals (999L, getValue.invoke(testData));
    }
}
&lt;/pre&gt;

&lt;p&gt;
This test case uses the following test data :
&lt;/p&gt;

&lt;pre&gt;
&lt;b&gt;package&lt;/b&gt; ch.niceideas.common.enhancer.testData;

&lt;b&gt;import&lt;/b&gt; ch.niceideas.common.enhancer.annotations.Data;

&lt;span style=&quot;color: green;&quot;&gt;/**
 * a test Data for the DataTest test case
 */&lt;/span&gt;
@Data
&lt;b&gt;public class&lt;/b&gt; TestData {

    &lt;b&gt;private int&lt;/b&gt; i = 0;

    &lt;b&gt;private&lt;/b&gt; String myString = &lt;span style=&quot;color: blue;&quot;&gt;&quot;abc&quot;&lt;/span&gt;;

    &lt;b&gt;private&lt;/b&gt; long value = -1;
}
&lt;/pre&gt;



&lt;a name=&quot;sec5&quot;&gt;&lt;/a&gt;
&lt;h2&gt;5. Conclusion &lt;/h2&gt;

&lt;p&gt;
Again. Bytecode manipulation opens a whole lot of new possibilities for the JVM and is key to address one of the biggest weakness of the JVM: the overwhelming verbosity of the language. The approaches and techniques presented above are extensively used by so many libraries and frameworks that have become the facto standard nowadays: AspectJ, Spring, Hibernate, Jprofiler, etc.
&lt;br&gt;
For that reason, and because it&apos;s really a lot of fun, one might find bytecode manipulation a pretty valuable mechanism to master. 
&lt;/p&gt;
&lt;p&gt;
In addition, even though Lombok uses for very good reasons a different technique (AST Transformation), I find it astonishing to see how bytecode manipulation enables a developer to mimic its features in so few lines of code.
&lt;/p&gt;
&lt;p&gt;
One can use bytecode manipulation to perform many tasks that would be difficult or impossible to do otherwise, and once one learns it, the sky is the limit. 
&lt;/p&gt;
&lt;p&gt;
Javassist put this power in hands of every Java developer in a simple, intuitive and efficient way.
&lt;/p&gt;
&lt;p&gt;
You might want to have a look at the first article in this serie available here : &lt;a href=&quot;https://www.niceideas.ch/roller2/badtrash/entry/bytecode-manipulation-with-javassist-for&quot;&gt;Bytecode manipulation with Javassist for fun and profit part I: Implementing a lightweight IoC container in 300 lines of code&lt;/a&gt;.
&lt;/p&gt;
&lt;p&gt;
Part of this article is available as a slideshare presentation here: &lt;a href=&quot;https://www.slideshare.net/JrmeKehrli/bytecode-manipulation-with-javassist-for-fun-and-profit&quot;&gt;https://www.slideshare.net/JrmeKehrli/bytecode-manipulation-with-javassist-for-fun-and-profit&lt;/a&gt;.
&lt;/p&gt;


</description>          </item>
    <item>
    <guid isPermaLink="true">https://www.niceideas.ch/roller2/badtrash/entry/bytecode-manipulation-with-javassist-for</guid>
    <title>Bytecode manipulation with Javassist for fun and profit part I: Implementing a lightweight IoC container in 300 lines of code</title>
    <dc:creator>Jerome Kehrli</dc:creator>
    <link>https://www.niceideas.ch/roller2/badtrash/entry/bytecode-manipulation-with-javassist-for</link>
        <pubDate>Mon, 13 Feb 2017 15:30:33 -0500</pubDate>
    <category>Java</category>
    <category>bytecode-manipulation</category>
    <category>ioc</category>
    <category>java</category>
    <category>javassist</category>
    <atom:summary type="html">&lt;p&gt;
Java bytecode is the form of instructions that the JVM executes. 
&lt;br&gt;
A Java programmer, normally, does not need to be aware of how Java bytecode works.
&lt;/p&gt;
&lt;p&gt;
Understanding the bytecode, however, is essential to the areas of tooling and program analysis, where the applications can modify the bytecode to adjust the behavior according to the application&apos;s domain. Profilers, mocking tools, AOP, ORM frameworks, IoC Containers, boilerplate code generators, etc. require to understand Java bytecode thoroughly and come up with means of manipulating it at runtime.
&lt;br&gt;
Each and every of these advanced features of what is nowadays standard approaches when programming with Java require a sound understanding of the Java bytecode, not to mention completely new languages running on the JVM such as Scala or Clojure.
&lt;/p&gt;
&lt;p&gt;
Bytecode manipulation is not easy though ... except with Javassist. 
&lt;br&gt;
Of all the libraries and tools providing advanced bytecode manipulation features, Javassist is the easiest to use and the quickest to master. It takes a few minutes to every initiated Java developer to understand and be able to use Javassist efficiently. And mastering bytecode manipulation, opens a whole new world of approaches and possibilities.
&lt;/p&gt;
&lt;p&gt;
The goal of this article is to present Javassist in the light of a concrete use case: the implementation in a little more than 300 lines of code of a lightweight, simple but cute IoC Container: SCIF - Simple and Cute IoC Framework.
&lt;/p&gt;</atom:summary>        <description>&lt;!-- Bytecode manipulation with Javassist for fun and profit part I: Implementing a lightweight IoC container in 300 lines of code --&gt;

&lt;p&gt;
Java bytecode is the form of instructions that the JVM executes. 
&lt;br&gt;
A Java programmer, normally, does not need to be aware of how Java bytecode works.
&lt;/p&gt;
&lt;p&gt;
Understanding the bytecode, however, is essential to the areas of tooling and program analysis, where the applications can modify the bytecode to adjust the behavior according to the application&apos;s domain. Profilers, mocking tools, AOP, ORM frameworks, IoC Containers, boilerplate code generators, etc. require to understand Java bytecode thoroughly and come up with means of manipulating it at runtime.
&lt;br&gt;
Each and every of these advanced features of what is nowadays standard approaches when programming with Java require a sound understanding of the Java bytecode, not to mention completely new languages running on the JVM such as Scala or Clojure.
&lt;/p&gt;
&lt;p&gt;
Bytecode manipulation is not easy though ... except with Javassist. 
&lt;br&gt;
Of all the libraries and tools providing advanced bytecode manipulation features, Javassist is the easiest to use and the quickest to master. It takes a few minutes to every initiated Java developer to understand and be able to use Javassist efficiently. And mastering bytecode manipulation, opens a whole new world of approaches and possibilities.
&lt;/p&gt;
&lt;p&gt;
The goal of this article is to present Javassist in the light of a concrete use case: the implementation in a little more than 300 lines of code of a lightweight, simple but cute IoC Container: SCIF - Simple and Cute IoC Framework.
&lt;/p&gt;
&lt;p&gt;
A new version of &lt;a href=&quot;https://www.niceideas.ch/roller2/badtrash/entry/comet-having-fun-with-the#sec31&quot;&gt;comet-tennis demo app&lt;/a&gt; with the SCIF framework integrated is available &lt;a download=&quot;comet_tennis_src_0.4.tar.gz&quot; type=&quot;application/tar+gzip&quot; href=&quot;https://www.niceideas.ch/roller2/badtrash/mediaresource/2eeba15c-dc3c-4546-adf8-a41cd4b31932&quot;&gt;here&lt;/a&gt;.
&lt;/p&gt;
&lt;p&gt;
Part of this article is available as a slideshare presentation here: &lt;a href=&quot;https://www.slideshare.net/JrmeKehrli/bytecode-manipulation-with-javassist-for-fun-and-profit&quot;&gt;https://www.slideshare.net/JrmeKehrli/bytecode-manipulation-with-javassist-for-fun-and-profit&lt;/a&gt;.
&lt;/p&gt;
&lt;p&gt;
You might also want to have a look at the second article in this serie available here : &lt;a href=&quot;https://www.niceideas.ch/roller2/badtrash/entry/bytecode-manipulation-with-javassist-for1&quot;&gt;Bytecode manipulation with Javassist for fun and profit part II: Generating toString and getter/setters using bytecode manipulation&lt;/a&gt;.
&lt;/p&gt;
&lt;p&gt;

&lt;b&gt;Summary&lt;/b&gt;
&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href=&quot;#sec1&quot;&gt;1. Introduction / Purpose &lt;/a&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href=&quot;#sec11&quot;&gt;1.1 Runtime Reflection&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;#sec12&quot;&gt;1.2 Bytcode manipulation&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;

&lt;li&gt;&lt;a href=&quot;#sec2&quot;&gt;2. Javassist&lt;/a&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href=&quot;#sec21&quot;&gt;2.1 Javassist prupose and behaviour&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;#sec22&quot;&gt;2.2 A gentle example with Javassist&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;

&lt;li&gt;&lt;a href=&quot;#sec3&quot;&gt;3. IoC&lt;/a&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href=&quot;#sec31&quot;&gt;3.1 IoC history&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;#sec32&quot;&gt;3.2 IoC Principle&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;#sec33&quot;&gt;3.2 IoC frameworks (Spring / Pico / Google)&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;

&lt;li&gt;&lt;a href=&quot;#sec4&quot;&gt;4.0 SCIF : Simple and Cute IoC Framework&lt;/a&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href=&quot;#sec41&quot;&gt;4.1 Principle&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;#sec42&quot;&gt;4.2 Design&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;#sec43&quot;&gt;4.3 Some focus on code&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;#sec44&quot;&gt;4.4 DemoApp : Comet Tennis&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;

&lt;li&gt;&lt;a href=&quot;#sec5&quot;&gt;5. Conclusion&lt;/a&gt;&lt;/li&gt;

&lt;/ul&gt;



&lt;a name=&quot;sec1&quot;&gt;&lt;/a&gt;
&lt;h2&gt;1. Introduction / Purpose &lt;/h2&gt;

&lt;p&gt;
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.
&lt;br&gt;
But first let&apos;s look at a very summarized view of the Java toolchain to remind a few concepts:
&lt;/p&gt;


&lt;div class=&quot;centering&quot;&gt;
&lt;a href=&quot;https://www.niceideas.ch/roller2/badtrash/mediaresource/583331b9-53d5-45a5-bb37-0277e7b58b95&quot;&gt;
&lt;img class=&quot;centered&quot; style=&quot;width: 500px; &quot; alt=&quot;Java Toolchain&quot; src=&quot;https://www.niceideas.ch/roller2/badtrash/mediaresource/583331b9-53d5-45a5-bb37-0277e7b58b95&quot; /&gt;
&lt;/a&gt;
&lt;/div&gt;
&lt;br&gt;

&lt;p&gt;
Java source files are compiled to Java class files by the Java Compiler. These Java classes take the form of &lt;i&gt;bytecode&lt;/i&gt;. This bytecode is loaded by the JVM to execute the Java program. 
&lt;br&gt;
In principle the bytecode is read only and cannot be change once loaded. That is true, but:
&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;The java classes bytecode can be modified before being loaded by the classloader through the usage of an &lt;i&gt;agent&lt;/i&gt;&lt;/li&gt;
&lt;li&gt;Classes bytecode can be modified at runtime without an agent as long as the class has not been loaded yet by a classloader.&lt;/li&gt;
&lt;li&gt;Classes can be generated entirely dynamically at runtime using bytecode manipulation techniques&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;
In this article we&apos;ll dig into the library &lt;a href=&quot;http://jboss-javassist.github.io/javassist/&quot;&gt;Javassist&lt;/a&gt; which is a bytecode manipulation framework that can help in achieving all of the above mechanisms.
&lt;br&gt;
But before, let&apos;s describe three different, unrelated but complementary techniques: &lt;i&gt;Introspection&lt;/i&gt;, &lt;i&gt;Reflection&lt;/i&gt; and &lt;i&gt;Bytecode Manipulation&lt;/i&gt;.
&lt;/p&gt;

&lt;a name=&quot;sec11&quot;&gt;&lt;/a&gt;
&lt;h3&gt;1.1 Runtime Reflection &lt;/h3&gt;

&lt;p&gt;
&lt;i&gt;Runtime reflection&lt;/i&gt; is the ability of a computer program to examine, introspect, and modify its own structure and behavior at runtime.
&lt;/p&gt;
&lt;p&gt;
Reflection is commonly used by programs which require the ability to examine or modify the runtime behavior of applications running in the Java virtual machine. 
&lt;br&gt;
Reflection is a powerful technique and can enable applications to perform operations which would otherwise be impossible.
&lt;/p&gt;
&lt;p&gt;
The ability to examine and manipulate a Java class from within itself may not sound like very much, but in other programming languages this feature simply doesn&apos;t exist. For example, there is no way in a Pascal, C, or C++ program to obtain detailed information about the functions defined within that program.
&lt;/p&gt;
&lt;p&gt;
In java there is no specific &lt;b&gt;introspection&lt;/b&gt; API available natively. &lt;i&gt;Introspection&lt;/i&gt; is performed as well using the &lt;b&gt;Java Reflection API&lt;/b&gt;.
&lt;/p&gt;
&lt;p&gt;
Still, conceptually, introspection and reflection are different things:
&lt;/p&gt;

&lt;div class=&quot;centering&quot;&gt;
&lt;a href=&quot;https://www.niceideas.ch/roller2/badtrash/mediaresource/dc4da8de-0885-4470-b0ae-0f392de9c4f3&quot;&gt;
&lt;img class=&quot;centered&quot; style=&quot;width: 600px;&quot; alt=&quot;Introspection and Reflection&quot; src=&quot;https://www.niceideas.ch/roller2/badtrash/mediaresource/dc4da8de-0885-4470-b0ae-0f392de9c4f3&quot; /&gt;
&lt;/a&gt;
&lt;/div&gt;
&lt;br&gt;

&lt;p&gt;
&lt;b&gt;Type introspection&lt;/b&gt; is the ability of a program to examine the type or properties of an object at runtime.
&lt;br&gt;
This is short example of Type Introspection in Java, where we discover the fields of an object and show their values dynamically. Again, Introspection in Java is really done using the &lt;i&gt;Reflection API&lt;/i&gt;
&lt;/p&gt;

&lt;pre&gt;
&lt;b&gt;import&lt;/b&gt; java.lang.reflect.Field;

&lt;b&gt;public class&lt;/b&gt; TestIntrospection {

    &lt;b&gt;public static class&lt;/b&gt; TestData {
        &lt;b&gt;private int&lt;/b&gt; i = &lt;span style=&quot;color: blue;&quot;&gt;0&lt;/span&gt;;
        &lt;b&gt;private&lt;/b&gt; String myString = &lt;span style=&quot;color: blue;&quot;&gt;&quot;abc&quot;&lt;/span&gt;;
        &lt;b&gt;private long&lt;/b&gt; value = &lt;span style=&quot;color: blue;&quot;&gt;-1&lt;/span&gt;;
    }

    &lt;span style=&quot;color: green;&quot;&gt;// test Introspection&lt;/span&gt;
    &lt;b&gt;public static void&lt;/b&gt; main (String[] args) {
        &lt;b&gt;try&lt;/b&gt; {
            &lt;span style=&quot;color: green;&quot;&gt;// Using Introspection, we really don&apos;t care of the actual type&lt;/span&gt;
            Object td = &lt;b&gt;new&lt;/b&gt; TestData();

            &lt;span style=&quot;color: green;&quot;&gt;// List fields of TestData and get their values&lt;/span&gt;
            &lt;b&gt;for&lt;/b&gt; (Field field : td.getClass().getDeclaredFields()) {
                field.setAccessible(&lt;b&gt;true&lt;/b&gt;); &lt;span style=&quot;color: green;&quot;&gt;// just make private fields accessible&lt;/span&gt;

                System.out.println (field.getName() + &lt;span style=&quot;color: blue;&quot;&gt;&quot;=&quot;&lt;/span&gt; + field.get(td));
            }
        } &lt;b&gt;catch&lt;/b&gt; (IllegalAccessException e) {
            e.printStackTrace();
        }
    }
}
&lt;/pre&gt;

&lt;p&gt;
&lt;b&gt;Runtime Reflection&lt;/b&gt; is a native feature in the Java programming language. It allows an executing Java program to examine or &quot;&lt;i&gt;introspect&lt;/i&gt;&quot; upon itself, and manipulate internal properties of the program.
&lt;br&gt;
A short example could be as follows, where we change the value of a field using reflection:
&lt;/p&gt;

&lt;pre&gt;
&lt;b&gt;import&lt;/b&gt; java.lang.reflect.Field;

&lt;b&gt;public class&lt;/b&gt; TestReflection {

    &lt;b&gt;public static class&lt;/b&gt; TestData {
        &lt;b&gt;private int&lt;/b&gt; i = &lt;span style=&quot;color: blue;&quot;&gt;0&lt;/span&gt;;
        &lt;b&gt;private&lt;/b&gt; String myString = &lt;span style=&quot;color: blue;&quot;&gt;&quot;abc&quot;&lt;/span&gt;;
        &lt;b&gt;private long&lt;/b&gt; value = &lt;span style=&quot;color: blue;&quot;&gt;-1&lt;/span&gt;;
    }

    &lt;span style=&quot;color: green;&quot;&gt;// test Reflection&lt;/span&gt;
    &lt;b&gt;public static void&lt;/b&gt; main (String[] args) {
        &lt;b&gt;try&lt;/b&gt; {
            &lt;span style=&quot;color: green;&quot;&gt;// Using Reflection, we really don&apos;t care of the actual type&lt;/span&gt;
            Object td = &lt;b&gt;new&lt;/b&gt; TestData();

            &lt;span style=&quot;color: green;&quot;&gt;// Change the value of the field myString&lt;/span&gt;
            Field myStringField =  td.getClass().getDeclaredField(&lt;span style=&quot;color: blue;&quot;&gt;&quot;myString&quot;&lt;/span&gt;);
            myStringField.setAccessible(&lt;b&gt;true&lt;/b&gt;); &lt;span style=&quot;color: green;&quot;&gt;// just make private fields accessible&lt;/span&gt;
            myStringField.set(td, &lt;span style=&quot;color: blue;&quot;&gt;&quot;xyz&quot;&lt;/span&gt;);

            System.out.println (myStringField.getName() + &lt;span style=&quot;color: blue;&quot;&gt;&quot;=&quot;&lt;/span&gt; + myStringField.get(td));

        } &lt;b&gt;catch&lt;/b&gt; (NoSuchFieldException | IllegalAccessException e) {
            e.printStackTrace();
        }
    }
}
&lt;/pre&gt;

&lt;p&gt;
&lt;i&gt;Runtime Reflection&lt;/i&gt; is a very powerful feature of the JVM. 
&lt;br&gt;
I wrote a &lt;a href=&quot;https://www.niceideas.ch/roller2/badtrash/entry/java-create-enum-instances-dynamically&quot;&gt;previous article&lt;/a&gt; on this very blog showing how to dynamically add values to an &lt;code&gt;Enum Type&lt;/code&gt; in Java using Runtime Reflection.
&lt;/p&gt;
&lt;p&gt;
&lt;b&gt;Why are those important in the scope of bytecode manipulation and Javassist ?&lt;/b&gt;
&lt;/p&gt;
&lt;p&gt;
&lt;i&gt;Runtime Reflection&lt;/i&gt; is important in our context for two reasons:
&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;First, because Javassist attempts to keep an API as close as possible to the Java Runtime Reflection API as a way to appear as natural as possible to Java developers.&lt;/li&gt;
&lt;li&gt;Second, and this is maybe more important, because behaviour injected in Java Classes using bytecode manipulation is not known by the compiler. Thus, it is sometimes only available through runtime reflection.&lt;/li&gt;
&lt;/ol&gt;


&lt;a name=&quot;sec12&quot;&gt;&lt;/a&gt;
&lt;h3&gt;1.2 Bytcode manipulation&lt;/h3&gt;

&lt;p&gt;
Bytecode manipulation allows the developer to express instructions in a format that is directly understood by the Java Virtual Machine, without passing from source code to bytecode through compiler.
&lt;br&gt;
Bytecode is somewhat similar to assembly code directly interpretable by the CPU. But with Java the bytecode is, first, interpreted by a Virtual Machine, the JVM, and second much more understandable that assembly code.
&lt;/p&gt;
&lt;p&gt;
One might wonder why one would want to get interested in bytecode manipulation and generation. As a matter of fact, every java developer has likely already been using bytecode manipulation all over the place without knowing it. 
&lt;br&gt;
Since the JVM can modify bytecode and use new bytecode while it is running, this generates a whole new universe of languages and tools that by far surpasses the initial intent of the Java language.
&lt;/p&gt;

&lt;div class=&quot;centering&quot;&gt;
&lt;a href=&quot;https://www.niceideas.ch/roller2/badtrash/mediaresource/18bc7da9-9a4d-40ab-8a0a-6430fafa6e3a&quot;&gt;
&lt;img class=&quot;centered&quot; style=&quot;width: 600px;&quot; alt=&quot;Bytecode Manipulation&quot; src=&quot;https://www.niceideas.ch/roller2/badtrash/mediaresource/18bc7da9-9a4d-40ab-8a0a-6430fafa6e3a&quot; /&gt;
&lt;/a&gt;
&lt;/div&gt;
&lt;br&gt;

&lt;p&gt;
&lt;b&gt;Bytecode manipulation use cases&lt;/b&gt;
&lt;/p&gt;
&lt;p&gt;
Some examples are:
&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;ORM frameworks such as &lt;a href=&quot;http://hibernate.org/&quot;&gt;Hibernate&lt;/a&gt; use bytecode manipulation to inject, for instance, relationship management code (lazy loading, etc.) inside mapped entities.&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;http://findbugs.sourceforge.net/&quot;&gt;FindBugs&lt;/a&gt; inspects bytecode for static code analysis&lt;/li&gt;
&lt;li&gt;Languages like &lt;a href=&quot;http://www.groovy-lang.org/&quot;&gt;Groovy&lt;/a&gt;, &lt;a href=&quot;https://www.scala-lang.org/&quot;&gt;Scala&lt;/a&gt;, &lt;a href=&quot;https://clojure.org/&quot;&gt;Clojure&lt;/a&gt; generate bytecode from different source code.&lt;/li&gt;
&lt;li&gt;IoC frameworks such as &lt;a href=&quot;https://spring.io/&quot;&gt;Spring&lt;/a&gt; use it to seamlessly weave your application lifecycle together&lt;/li&gt;
&lt;li&gt;language extensions like &lt;a href=&quot;http://www.eclipse.org/aspectj/&quot;&gt;AspectJ&lt;/a&gt; can augment the capabilities of Java by modifying the classes that the Java compiler generated&lt;/li&gt;
&lt;li&gt;etc.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;
The Java platform provides you with many ways to work with bytecode, for instance:
&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;One can write his own compiler for any kind of new and crazy language&lt;/li&gt;
&lt;li&gt;One can generate on the fly sub-classes of already loaded classes and use them instead of original classes to get additional behaviour&lt;/li&gt;
&lt;li&gt;One can write an instrumentation agent that plugs right into the JVM and modifies behaviour of classes before they are loaded by the classloader&lt;/li&gt;
&lt;li&gt;etc.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;
With so many options available, one of these will certainly fit any experiment that one wants to play around with. With bytecode manipulation, one really gets the whole power of the JVM for free and the capacity to slot in any idea exactly where it&apos;s needed while reusing the rest of the Java platform.
&lt;/p&gt;
&lt;p&gt;
From my perspective, this is what excites me the most, as a developer I can really focus on my crazy idea that is not supported by the Java language and I don&apos;t have to write an entire platform to make it come to life. 
&lt;br&gt;
Certainly this has been one of the key areas why the Java community has constantly been experimenting with new ways to push the programming toolset further.
&lt;/p&gt;
&lt;p&gt;
This article wont present the details of the Java bytecode any further. We&apos;ll focus instead on high level libraries aimed at manipulating the Java Bytecode.
&lt;br&gt;
Should you be interested in the low level details, I can only recommend that you read &lt;a href=&quot;https://niceideas.ch//mastering-java-bytecode.pdf&quot;&gt;this excellent paper from ZeroTunaround&lt;/a&gt;, the guys behind JRebel.
&lt;/p&gt;
&lt;p&gt;
&lt;b&gt;Most common bytecode manipulation libraries&lt;/b&gt;
&lt;/p&gt;
&lt;p&gt;
As a matter of fact, while Runtime Reflection is supported natively by the JVM, &lt;b&gt;Bytecode manipulation&lt;/b&gt;, on the other hand, is fairly difficult to achieve without the usage of &lt;i&gt;a specific library&lt;/i&gt;
&lt;/p&gt;
&lt;p&gt;
The most common bytecode manipulation libraries in Java are as follows:
&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href=&quot;http://asm.ow2.org/&quot;&gt;ASM&lt;/a&gt; s a project of the OW2 Consortium. It provides a simple API for decomposing, modifying, and recomposing binary Java classes. ASM exposes the internal aggregate components of a given Java class through its visitor oriented API. ASM also provides, on top of this visitor API, a tree API that represents classes as object constructs. Both APIs can be used for modifying the binary bytecode, as well as generating new bytecode&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;https://commons.apache.org/proper/commons-bcel/&quot;&gt;BCEL&lt;/a&gt;  provides a simple library that exposes the internal aggregate components of a given Java class through its API as object constructs (as opposed to the disassembly of the lower-level opcodes). These objects also expose operations for modifying the binary bytecode, as well as generating new bytecode (via injection of new code into the existing code, or through generation of new classes altogether).&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;https://github.com/cglib/cglib/wiki&quot;&gt;CGLIB&lt;/a&gt; is a powerful, high performance and quality Code Generation Library, it is used to extend JAVA classes and implements interfaces at runtime. CGLIB is really oriented towards implementing new classes at runtime, as opposed to modifying existing bytecode such as other libraries.&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;http://jboss-javassist.github.io/javassist/&quot;&gt;Javassist&lt;/a&gt; is a Java library providing a means to manipulate the Java bytecode of an application. In this sense Javassist provides the support for structural reflection, i.e. the ability to change the implementation of a class at run time.&lt;/li&gt; 
&lt;/ul&gt;

&lt;p&gt;
Javassist is much easier to use that lower level libraries such as BCEL or ASM. It is also less limited and more powerful than CGLIB.
&lt;/p&gt;
&lt;p&gt;
This chart shows in addition the AspectJ framework, as a way to have the user get an understanding of the level of abstraction provided by these tools:
&lt;/p&gt;

&lt;div class=&quot;centering&quot;&gt;
&lt;a href=&quot;https://www.niceideas.ch/roller2/badtrash/mediaresource/08231a71-0633-4a02-934f-a968d20cbe69&quot;&gt;
&lt;img class=&quot;centered&quot; style=&quot;width: 500px;&quot; alt=&quot;Bytecode Manipulation frameworks&quot; src=&quot;https://www.niceideas.ch/roller2/badtrash/mediaresource/08231a71-0633-4a02-934f-a968d20cbe69&quot; /&gt;
&lt;/a&gt;
&lt;/div&gt;
&lt;br&gt;

&lt;p&gt;
Now, as you might have guessed from its title, this rest of this article will focus on Javassist.
&lt;/p&gt;

&lt;a name=&quot;sec2&quot;&gt;&lt;/a&gt;
&lt;h2&gt;2. Javassist&lt;/h2&gt;

&lt;p&gt;
From the &lt;a href=&quot;http://jboss-javassist.github.io/javassist/&quot;&gt;Javassist web site:&lt;/a&gt;
&lt;/p&gt;
&lt;p&gt;
&quot;Javassist (Java Programming Assistant) makes Java bytecode manipulation simple. It is a class library for editing bytecode in Java; it enables Java programs to define a new class at runtime and to modify a class file when the JVM loads it. 
&lt;br&gt;
Unlike other similar bytecode editors, Javassist provides two levels of API: source level and bytecode level. If the users use the source-level API, they can edit a class file without knowledge of the specifications of the Java bytecode. 
&lt;br&gt;
The whole API is designed with only the vocabulary of the Java language. You can even specify inserted bytecode in the form of source text; Javassist compiles it on the fly. On the other hand, the bytecode-level API allows the users to directly edit a class file as other editors.&quot;
&lt;/p&gt;
&lt;p&gt;
The fact that Javassist is presented above as being able to modify classes at loading time is not a limitation of the Javassist framework itself, but rather a consequence from the linking system of the JVM. Once a class has already been loaded, changing it would result in a Linkage Error (unless the JVM is launched with the JPDA [Java Platform Debugger Architecture] enabled, which would make a class dynamically reloadable, but that is another story).
&lt;br&gt;
Interestingly, Javasssist is perfectly able to modify a class long after the application has started as long as that specific class has not been loaded.
&lt;br&gt;
This is just to emphasize that Javassist can perfectly be used to modify classes at runtime and not only at &quot;&lt;i&gt;pre-main&lt;/i&gt;&quot; time by the usage of a JVM agent, even though this suffers from great constraints.
&lt;/p&gt;
&lt;p&gt;
In my opinion, the great strength of Javassist over its competitors is that Javassist enables the user to generate bytecode on the fly from actual Java code given to it in the form of a string by calling the Java Compiler on the fly on such strings.
&lt;br&gt;
And that is freaking awesome.
&lt;/p&gt;

&lt;a name=&quot;sec21&quot;&gt;&lt;/a&gt;
&lt;h3&gt;2.1 Javassist purpose and behaviour&lt;/h3&gt;

&lt;p&gt;
Javassist provides the developer with a high level API around classes, methods, fields, etc. aimed at making it as easy as possible to change the implementation of existing classes or even implement completely new classes, dynamically, at runtime, using bytecode manipulation.
&lt;/p&gt;
&lt;p&gt;
(The following is explained in more details in the &lt;a href=&quot;http://jboss-javassist.github.io/javassist/tutorial/tutorial.html&quot;&gt;official Javassist tutorial&lt;/a&gt;.)
&lt;/p&gt;
&lt;p&gt;
The most important elements of the Javassist API are presented on the schema below:
&lt;/p&gt;

&lt;div class=&quot;centering&quot;&gt;
&lt;a href=&quot;https://www.niceideas.ch/roller2/badtrash/mediaresource/10735f16-d4b1-4bc8-8a4e-e70761f85b4b&quot;&gt;
&lt;img class=&quot;centered&quot; style=&quot;width: 500px;&quot; alt=&quot;Javassist API&quot; src=&quot;https://www.niceideas.ch/roller2/badtrash/mediaresource/10735f16-d4b1-4bc8-8a4e-e70761f85b4b&quot; /&gt;
&lt;/a&gt;
&lt;/div&gt;
&lt;br&gt;

&lt;p&gt;
The &lt;code&gt;class Javassist.CtClass&lt;/code&gt; is an abstract representation of a class file. A &lt;code&gt;CtClass&lt;/code&gt; (compile-time class) object is a handle for dealing with a class file. The following program is a very simple example:
&lt;/p&gt;
&lt;p&gt;
(In all examples of code from now on, &lt;code&gt;&lt;span style=&quot;color: DarkRed&quot;&gt;I will be coloring relevant Javassist API calls in dark red&lt;/span&gt;&lt;/code&gt;)
&lt;/p&gt;

&lt;pre&gt;
&lt;span style=&quot;color: DarkRed&quot;&gt;ClassPool&lt;/span&gt; pool = &lt;span style=&quot;color: DarkRed&quot;&gt;ClassPool.getDefault()&lt;/span&gt;;
&lt;span style=&quot;color: DarkRed&quot;&gt;CtClass&lt;/span&gt; cc = pool.&lt;span style=&quot;color: DarkRed&quot;&gt;get&lt;/span&gt;(&lt;span style=&quot;color: blue;&quot;&gt;&quot;test.Rectangle&quot;&lt;/span&gt;);
cc.&lt;span style=&quot;color: DarkRed&quot;&gt;setSuperclass&lt;/span&gt;(pool.&lt;span style=&quot;color: DarkRed&quot;&gt;get&lt;/span&gt;(&lt;span style=&quot;color: blue;&quot;&gt;&quot;test.Point&quot;&lt;/span&gt;));
cc.&lt;span style=&quot;color: DarkRed&quot;&gt;writeFile()&lt;/span&gt;;
&lt;/pre&gt;

&lt;p&gt;
&lt;b&gt;&lt;code&gt;ClassPool&lt;/code&gt;&lt;/b&gt;
&lt;/p&gt;
&lt;p&gt;
This program first obtains a &lt;code&gt;ClassPool&lt;/code&gt; object, which controls bytecode modification with Javassist. The &lt;code&gt;ClassPool&lt;/code&gt; object is a container of &lt;code&gt;CtClass&lt;/code&gt; object representing a class file. It reads a class file on demand for constructing a &lt;code&gt;CtClass&lt;/code&gt; object and records the constructed object for responding later accesses. 
&lt;/p&gt;
&lt;p&gt;
To modify the definition of a class, the users must first obtain from a &lt;code&gt;ClassPool&lt;/code&gt; object a reference to a &lt;code&gt;CtClass&lt;/code&gt; object representing that &lt;code&gt;class.get()&lt;/code&gt; in &lt;code&gt;ClassPool&lt;/code&gt; is used for this purpose. 
&lt;br&gt;
In the case of the program shown above, the &lt;code&gt;CtClass&lt;/code&gt; object representing a class &lt;code&gt;test.Rectangle&lt;/code&gt; is obtained from the &lt;code&gt;ClassPool&lt;/code&gt; object and it is assigned to a variable &lt;code&gt;cc&lt;/code&gt;. The &lt;code&gt;ClassPool&lt;/code&gt; object returned by &lt;code&gt;getDefault()&lt;/code&gt; searches the default system search path.
&lt;/p&gt;
&lt;p&gt;
&lt;b&gt;&lt;code&gt;CtClass&lt;/code&gt;&lt;/b&gt;
&lt;/p&gt;
&lt;p&gt;
The &lt;code&gt;CtClass&lt;/code&gt; object obtained from a &lt;code&gt;ClassPool&lt;/code&gt; object can be modified. 
&lt;br&gt;
In the example above, it is modified so that the superclass of &lt;code&gt;test.Rectangle&lt;/code&gt; is changed into a class &lt;code&gt;test.Point&lt;/code&gt;. This change is reflected on the original class file when &lt;code&gt;writeFile()&lt;/code&gt; in &lt;code&gt;CtClass()&lt;/code&gt; is finally called.
&lt;/p&gt;
&lt;p&gt;
&lt;code&gt;writeFile()&lt;/code&gt; translates the &lt;code&gt;CtClass&lt;/code&gt; object into a class file and writes it on a local disk. Javassist also provides a method for directly obtaining the modified bytecode. To obtain the bytecode, call &lt;code&gt;toBytecode()&lt;/code&gt;:
&lt;/p&gt;

&lt;pre&gt;
&lt;b&gt;byte&lt;/b&gt;[] b = cc.&lt;span style=&quot;color: DarkRed&quot;&gt;toBytecode&lt;/span&gt;();
&lt;/pre&gt;

&lt;p&gt;
(Bear in mind that this is especially useful when implementing a Java agent)
&lt;/p&gt;
&lt;p&gt;
You can directly load the &lt;code&gt;CtClass&lt;/code&gt; as well:
&lt;/p&gt;

&lt;pre&gt;
Class clazz = cc.&lt;span style=&quot;color: DarkRed&quot;&gt;toClass&lt;/span&gt;();
&lt;/pre&gt;

&lt;p&gt;
A class can be returned to the pool, making it available to the classloader and hence the whole application:
&lt;/p&gt;

&lt;pre&gt;
pool.&lt;span style=&quot;color: DarkRed&quot;&gt;toClass&lt;/span&gt;(cc, Thread.currentThread().getContextClassLoader(), &lt;b&gt;null&lt;/b&gt;);
&lt;/pre&gt;

&lt;p&gt;
&lt;b&gt;Defining a new class&lt;/b&gt;
&lt;/p&gt;
&lt;p&gt;
To define a new class from scratch, &lt;code&gt;makeClass()&lt;/code&gt; must be called on a &lt;code&gt;ClassPool&lt;/code&gt;.
&lt;/p&gt;

&lt;pre&gt;
&lt;span style=&quot;color: DarkRed&quot;&gt;ClassPool&lt;/span&gt; pool = &lt;span style=&quot;color: DarkRed&quot;&gt;ClassPool.getDefault&lt;/span&gt;();
&lt;span style=&quot;color: DarkRed&quot;&gt;CtClass&lt;/span&gt; cc = pool.&lt;span style=&quot;color: DarkRed&quot;&gt;makeClass&lt;/span&gt;(&lt;span style=&quot;color: blue;&quot;&gt;&quot;Circle&quot;&lt;/span&gt;);
cc.&lt;span style=&quot;color: DarkRed&quot;&gt;setSuperclass&lt;/span&gt;(pool.&lt;span style=&quot;color: DarkRed&quot;&gt;get&lt;/span&gt;(&lt;span style=&quot;color: blue;&quot;&gt;&quot;test.Point&quot;&lt;/span&gt;));
&lt;/pre&gt;

&lt;p&gt;
This program defines a class &lt;code&gt;Circle&lt;/code&gt; including no members except those inherited by the parent class &lt;code&gt;Point&lt;/code&gt;. Member methods of &lt;code&gt;Circle&lt;/code&gt; can afterwards be created with factory methods declared in &lt;code&gt;CtNewMethod&lt;/code&gt; and appended to &lt;code&gt;Circle&lt;/code&gt; with &lt;code&gt;addMethod()&lt;/code&gt; in &lt;code&gt;CtClass&lt;/code&gt;.
&lt;br&gt;
&lt;code&gt;makeClass()&lt;/code&gt; cannot create a new interface; &lt;code&gt;makeInterface()&lt;/code&gt; in &lt;code&gt;ClassPool&lt;/code&gt; can do. Member methods in an interface can be created with &lt;code&gt;abstractMethod()&lt;/code&gt; in &lt;code&gt;CtNewMethod&lt;/code&gt;. Note that an interface method is an abstract method.
&lt;/p&gt;
&lt;p&gt;
&lt;b&gt;Implementing / Modifying a class&lt;/b&gt;
&lt;/p&gt;
&lt;p&gt;
Methods are represented by &lt;code&gt;CtMethod&lt;/code&gt; objects. &lt;code&gt;CtMethod&lt;/code&gt; provides several methods for modifying the definition of the method. Note that if a method is inherited from a super class, then the same &lt;code&gt;CtMethod&lt;/code&gt; object that represents the inherited method represents the method declared in that super class. A &lt;code&gt;CtMethod&lt;/code&gt; object corresponds to every method declaration.
&lt;br&gt;
Constructors are represented by their very own type in Javassist : &lt;code&gt;CtConstructor&lt;/code&gt;. Both &lt;code&gt;CtMethod&lt;/code&gt; and &lt;code&gt;CtConstructor&lt;/code&gt; extends the same base class and have a lot of their API in common.
&lt;/p&gt;
&lt;p&gt;
Javassist does not allow to remove a method or field, but it allows to change the name. So if a method is not necessary any more, it should be renamed and changed to be a private method by calling &lt;code&gt;setName()&lt;/code&gt; and &lt;code&gt;setModifiers()&lt;/code&gt; declared in CtMethod, for instance to hide it. But beware of linkage errors at runtime if you mess with a method used by another class.
&lt;/p&gt;
&lt;p&gt;
&lt;code&gt;CtMethod&lt;/code&gt; and &lt;code&gt;CtConstructor&lt;/code&gt; can be used to completely implement / rewrite a constructor or a method from scratch. They also provide methods &lt;code&gt;insertBefore()&lt;/code&gt;, &lt;code&gt;insertAfter()&lt;/code&gt;, and &lt;code&gt;addCatch()&lt;/code&gt;. They are used for inserting a code fragment into the body of an existing method.
&lt;/p&gt;
&lt;p&gt;
When implementing or rewriting completely a method from scratch, using &lt;code&gt;CtNewMethod.make()&lt;/code&gt; is in my opinion the most convenient approach. It enables the developer to &lt;b&gt;implement a method by providing Java Source Code&lt;/b&gt; syntax in a simple string.
&lt;br&gt;
For instance:
&lt;/p&gt;

&lt;pre&gt;
&lt;span style=&quot;color: DarkRed&quot;&gt;CtClass&lt;/span&gt; point = &lt;span style=&quot;color: DarkRed&quot;&gt;ClassPool.getDefault().get&lt;/span&gt;(&lt;span style=&quot;color: blue;&quot;&gt;&quot;Point&quot;&lt;/span&gt;);
&lt;span style=&quot;color: DarkRed&quot;&gt;CtMethod&lt;/span&gt; m = &lt;span style=&quot;color: DarkRed&quot;&gt;CtNewMethod.make&lt;/span&gt;(
        &lt;span style=&quot;color: blue;&quot;&gt;&quot;public int xmove(int dx) { x += dx; }&quot;&lt;/span&gt;,
        point);
point.&lt;span style=&quot;color: DarkRed&quot;&gt;addMethod&lt;/span&gt;(m);
&lt;/pre&gt;

&lt;p&gt;
&lt;code&gt;CtNewMethod&lt;/code&gt; provides a lot of high level methods for implementing getters, setters and other commodity methods directly, sometimes even without having to bother providing an implementation on your own.
&lt;/p&gt;
&lt;p&gt;
Some pretty complete information in this regards is available on the &lt;a href=&quot;http://jboss-javassist.github.io/javassist/tutorial/tutorial2.html&quot;&gt;Second official javassist tutorial&lt;/a&gt;.
&lt;/p&gt;

&lt;a name=&quot;sec22&quot;&gt;&lt;/a&gt;
&lt;h3&gt;2.2 A gentle example with Javassist&lt;/h3&gt;

&lt;p&gt;
We&apos;ll see now a simple and yet complete example using Javassist. We&apos;ll implement the getters and setters for the fields of the class &lt;code&gt;TestData&lt;/code&gt; introduced &lt;a href=&quot;#sec11&quot;&gt;here&lt;/a&gt; using bytecode manipulation.
&lt;br&gt;
Then we&apos;ll test the getter and setter for the field &lt;code&gt;myString&lt;/code&gt;. Since these getters and setters are injected using bytecode manipulation at runtime, we&apos;ll have to use runtime reflection to call them:
&lt;/p&gt;
&lt;p&gt;
(Reminder, &lt;code&gt;&lt;span style=&quot;color: DarkRed&quot;&gt;I am coloring relevant Javassist API calls in dark red&lt;/span&gt;&lt;/code&gt;)
&lt;/p&gt;

&lt;pre&gt;
&lt;b&gt;import&lt;/b&gt; javassist.*;

&lt;b&gt;import&lt;/b&gt; java.lang.reflect.InvocationTargetException;
&lt;b&gt;import&lt;/b&gt; java.lang.reflect.Method;

&lt;b&gt;public class&lt;/b&gt; TestJavassist {

    &lt;b&gt;public static class&lt;/b&gt; TestData {
        &lt;b&gt;private int&lt;/b&gt; i = &lt;span style=&quot;color: blue;&quot;&gt;0&lt;/span&gt;;
        &lt;b&gt;private&lt;/b&gt; String myString = &lt;span style=&quot;color: blue;&quot;&gt;&quot;abc&quot;&lt;/span&gt;;
        &lt;b&gt;private long&lt;/b&gt; value = &lt;span style=&quot;color: blue;&quot;&gt;-1&lt;/span&gt;;
    }

    &lt;span style=&quot;color: green;&quot;&gt;// test Javassist&lt;/span&gt;
    &lt;b&gt;public static void&lt;/b&gt; main (String[] args) {
        &lt;b&gt;try&lt;/b&gt; {

            &lt;span style=&quot;color: DarkRed&quot;&gt;ClassPool&lt;/span&gt; cp = &lt;span style=&quot;color: DarkRed&quot;&gt;ClassPool.getDefault&lt;/span&gt;();
            &lt;span style=&quot;color: DarkRed&quot;&gt;CtClass&lt;/span&gt; clazz = cp.&lt;span style=&quot;color: DarkRed&quot;&gt;get&lt;/span&gt;(&lt;span style=&quot;color: blue;&quot;&gt;&quot;ch.niceideas.common.utils.TestJavassist$TestData&quot;&lt;/span&gt;);

            &lt;b&gt;for&lt;/b&gt; (&lt;span style=&quot;color: DarkRed&quot;&gt;CtField&lt;/span&gt; field : clazz.&lt;span style=&quot;color: DarkRed&quot;&gt;getDeclaredFields&lt;/span&gt;()) {
                String camelCaseField = field.getName().substring(&lt;span style=&quot;color: blue;&quot;&gt;0&lt;/span&gt;, &lt;span style=&quot;color: blue;&quot;&gt;1&lt;/span&gt;).toUpperCase()
                        + field.getName().substring(&lt;span style=&quot;color: blue;&quot;&gt;1&lt;/span&gt;);

                &lt;span style=&quot;color: green;&quot;&gt;// We don&apos;t need to mess with implementation here. CtnewMethod has a&lt;/span&gt;
                &lt;span style=&quot;color: green;&quot;&gt;// commodity method to implement a getter directly&lt;/span&gt;
                &lt;span style=&quot;color: DarkRed&quot;&gt;CtMethod&lt;/span&gt; fieldGetter = &lt;span style=&quot;color: DarkRed&quot;&gt;CtNewMethod.getter&lt;/span&gt;(&lt;span style=&quot;color: blue;&quot;&gt;&quot;get&quot;&lt;/span&gt; + camelCaseField, field);
                clazz.&lt;span style=&quot;color: DarkRed&quot;&gt;addMethod&lt;/span&gt;(fieldGetter);

                &lt;span style=&quot;color: green;&quot;&gt;// Just for the sake of an example, we&apos;ll define the setter by actually&lt;/span&gt;
                &lt;span style=&quot;color: green;&quot;&gt;// providing the implementation, not using the commodity method offered&lt;/span&gt;
                &lt;span style=&quot;color: green;&quot;&gt;// by CtNewMethod&lt;/span&gt;
                &lt;span style=&quot;color: DarkRed&quot;&gt;CtMethod&lt;/span&gt; fieldSetter = &lt;span style=&quot;color: DarkRed&quot;&gt;CtNewMethod.make&lt;/span&gt;(
                            &lt;span style=&quot;color: blue;&quot;&gt;&quot;public void set&quot;&lt;/span&gt; + camelCaseField + &lt;span style=&quot;color: blue;&quot;&gt;&quot; \n&quot;&lt;/span&gt; + 
                            &lt;span style=&quot;color: blue;&quot;&gt;&quot;    (&quot;&lt;/span&gt; + field.getType().getName() + &lt;span style=&quot;color: blue;&quot;&gt;&quot; param) { \n&quot;&lt;/span&gt; +
                            &lt;span style=&quot;color: blue;&quot;&gt;&quot;    this.&quot;&lt;/span&gt; + field.getName() + &lt;span style=&quot;color: blue;&quot;&gt;&quot; = param; \n&quot;&lt;/span&gt; +
                            &lt;span style=&quot;color: blue;&quot;&gt;&quot;}&quot;&lt;/span&gt;,
                        clazz);
                clazz.&lt;span style=&quot;color: DarkRed&quot;&gt;addMethod&lt;/span&gt;(fieldSetter);
            }

            &lt;span style=&quot;color: green;&quot;&gt;// Save class and make it available&lt;/span&gt;
            cp.&lt;span style=&quot;color: DarkRed&quot;&gt;toClass&lt;/span&gt;(clazz, Thread.currentThread().getContextClassLoader(), &lt;b&gt;null&lt;/b&gt;);

            &lt;span style=&quot;color: green;&quot;&gt;// Now instantiate a new TestData&lt;/span&gt;
            TestData td = &lt;b&gt;new&lt;/b&gt; TestData();

            &lt;span style=&quot;color: green;&quot;&gt;// Get the value of the field &apos;myString&apos; using the newly defined getter&lt;/span&gt;
            Method getter =  td.getClass().getDeclaredMethod(&lt;span style=&quot;color: blue;&quot;&gt;&quot;getMyString&quot;&lt;/span&gt;);
            System.out.println (getter.invoke(td));

            &lt;span style=&quot;color: green;&quot;&gt;// Change the value of field &apos;myString&apos; using newly defined setter&lt;/span&gt;
            Method setter =  td.getClass().getDeclaredMethod(&lt;span style=&quot;color: blue;&quot;&gt;&quot;setMyString&quot;&lt;/span&gt;, String.&lt;b&gt;class&lt;/b&gt;);
            setter.invoke(td, &lt;span style=&quot;color: blue;&quot;&gt;&quot;xyz&quot;&lt;/span&gt;);

            &lt;span style=&quot;color: green;&quot;&gt;// Get the value again&lt;/span&gt;
            System.out.println (getter.invoke(td));

        } &lt;b&gt;catch&lt;/b&gt; (  NotFoundException | CannotCompileException | NoSuchMethodException
                 | IllegalAccessException | InvocationTargetException e) {
            e.printStackTrace();
        }
    }
}
&lt;/pre&gt;


&lt;a name=&quot;sec3&quot;&gt;&lt;/a&gt;
&lt;h2&gt;3. IoC&lt;/h2&gt;

&lt;p&gt;
OK. Since the example code I want to implement below with Javassist is a simple IoC container, I guess I should present what IoC actually is beforehand.
&lt;/p&gt;
&lt;p&gt;
&lt;b&gt;Inversion of Control&lt;/b&gt; is a design pattern related to lifecycle management of components in an application benefiting from a services architecture. 
&lt;br&gt;
In such an application, business components are usually implemented in the form of various services, such as business services, business managers, DAOs, etc. The main class delegates specific business concerns to business services, which delegate finer aspects in their turn to managers, which further delegate various business of technical aspects to smaller managers, or DAOs, adapters. etc.
&lt;/p&gt;
&lt;p&gt;
These various services need to know about each others to be able to call each others. Managing the construction and instantiation of these services is called &lt;i&gt;components lifecycle management&lt;/i&gt;.
&lt;/p&gt;
&lt;p&gt;
Very often, business services are stateless components, not keeping any state in instance variables or else. Traditionally, for a very long time, these stateless services have been implemented as &lt;i&gt;singletons&lt;/i&gt;. For a very long time this was a very convenient approach since the main singleton simply needs to &lt;i&gt;get&lt;/i&gt; the other singletons it was using, which in turn simply needed to get the other singletons they were using, and so on.
&lt;br&gt;
By separating the instantiation of singletons and their initialization in two stages, cycles could be handled easily and everyone was happy.
&lt;br&gt;
But with the rise of XP and unit testing, singleton-based applications were suffering from a very critical drawback:
&lt;/p&gt;
&lt;p&gt;
Singletons were enforcing strict dependencies on other service implementation at compile time, making it pretty impossible to replace the dependencies by mock objects or stubs as required for efficiently unit testing a specific service.
&lt;br&gt;
Using singletons, testing a specific service often meant to be required to completely build and initialize the whole application, which can well turn into a nightmare.
&lt;/p&gt;
&lt;p&gt;
Java EE was of course not an answer to this problem since it required to have a Java EE container, which is even more of a nightmare (well let&apos;s not get me started on Java EE, shall we ?).
&lt;/p&gt;
&lt;p&gt;
&lt;b&gt;Inversion of Control&lt;/b&gt;
&lt;/p&gt;
&lt;p&gt;
Inversion of control is initially mostly an answer to this problem, as a way to increase the modularity of the application and making it more extensible, and more importantly testable in an easier way by removing the strict dependencies between components.
&lt;br&gt;
The key idea is to delegate the management of the lifecycle of the components and the injection of each component&apos;s dependencies to a framework, or rather a container, borrowing the term from Java EE, called here a &lt;b&gt;lightweight container&lt;/b&gt;.
&lt;/p&gt;
&lt;p&gt;
Instead of every component getting each other references on the singletons or specific instances by building them, the container takes care of &lt;b&gt;instantiating the components&lt;/b&gt;, managing their lifecycle in the required scope, and &lt;b&gt;injecting their dependencies&lt;/b&gt; at runtime.
&lt;br&gt;
Injecting the dependencies at runtime, with a configurable approach, using a configuration file, annotations or even a dedicated API, opens the possibility to inject a different implementation of a service depending on the context, as long as it respects the required interface.
&lt;br&gt;
For instance, injecting a &lt;i&gt;mock object&lt;/i&gt; instead of the real deal for unit testing becomes straightforward.
&lt;/p&gt;
&lt;p&gt;
&lt;i&gt;Inversion of Control&lt;/i&gt; and &lt;i&gt;Dependency Injection&lt;/i&gt; are two different things - and yet strongly related to each other - often confused in some documentation:
&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;b&gt;Inversion of Control&lt;/b&gt; - IoC : is the name of the design pattern, the approach. It is considered a design pattern, which, in my opinion, is wrong! IoC is an &lt;i&gt;architecture pattern&lt;/i&gt;. But yeah that is really no big deal.&lt;/li&gt;
&lt;li&gt;&lt;b&gt;Dependency Injection&lt;/b&gt; - DI : is the name of a technique, a mechanism on which IoC often relies to take place. It consists in injecting the components required by a specific component at runtime, based on some configuration rules. DI is really just one aspect of IoC.
&lt;/ul&gt;


&lt;a name=&quot;sec31&quot;&gt;&lt;/a&gt;
&lt;h3&gt;3.1 IoC history&lt;/h3&gt;

&lt;p&gt;
Inversion of Control, as a term, was popularized in 1998 by the Apache Avalon team trying to engineer a &quot;&lt;i&gt;Java Apache Server Framework&lt;/i&gt;&quot; for the growing set of server side Java components and tools at Apache.&lt;br&gt;
To the Avalon team, it was clear that components receiving various aspects of component assembly, configuration and lifecycle was a superior design to those components going at getting the same themselves.
&lt;/p&gt;
&lt;p&gt;
Later, the authors of the &quot;&lt;i&gt;Java Open Source Programming&lt;/i&gt;&quot; book wrote XWork and WebWork2 to support their forthcoming book. Their concepts were very much like those from IoC/Avalon, but dependencies were passed into the component via setters. The need for those dependencies was declared in some accompanying XML.
&lt;br&gt;
That was actually the first IoC framework close to the form they have today.
&lt;/p&gt;
&lt;p&gt;
In 2002, Rod Johnson, leader of the Spring Framework wrote the book &quot;&lt;i&gt;Expert One-on-One : J2EE Design and Development&lt;/i&gt;&quot; that also discussed the concepts of setter injection, and introduced the codeline that ultimately became the Spring Framework at SourceForge in February of 2003.
&lt;br&gt;
I myself discovered the concept in 2003 when reading that book, following the advise of Mr. Parick Gras, which I take the opportunity to thank a lot for this here.
&lt;/p&gt;
&lt;p&gt;
This whole history is presented in details on &lt;a href=&quot;http://picocontainer.com/inversion-of-control-history.html&quot;&gt;PicoContainer / Inversion of Control History&lt;/a&gt; and can be represented as follows:
&lt;/p&gt;

&lt;div class=&quot;centering&quot;&gt;
&lt;a href=&quot;https://www.niceideas.ch/roller2/badtrash/mediaresource/859f9a17-9503-486d-b5ca-310cf6c3e4ca&quot;&gt;
&lt;img class=&quot;centered&quot; style=&quot;width: 691px;&quot; alt=&quot;IoC history timeline&quot; src=&quot;https://www.niceideas.ch/roller2/badtrash/mediaresource/859f9a17-9503-486d-b5ca-310cf6c3e4ca&quot; /&gt;
&lt;/a&gt;&lt;br&gt;
&lt;div class=&quot;centered&quot;&gt;
(Source : &lt;a href=&quot;http://picocontainer.com/inversion-of-control-history.html&quot;&gt;PicoContainer / Inversion of Control History&lt;/a&gt;)
&lt;/div&gt;
&lt;/div&gt;
&lt;br&gt;


&lt;a name=&quot;sec32&quot;&gt;&lt;/a&gt;
&lt;h3&gt;3.2 IoC Principle&lt;/h3&gt;

&lt;p&gt;
As stated above, in a usual application, the lifecycle of components starts with a main component (or class) that either creates the other services it requires or get their singletons.
&lt;br&gt;
These other components, in their turn, create or get references on their own dependencies, and so on.
&lt;/p&gt;

&lt;div class=&quot;centering&quot;&gt;
&lt;a href=&quot;https://www.niceideas.ch/roller2/badtrash/mediaresource/a8688128-c6be-4993-9328-1e8506ca2bc7&quot;&gt;
&lt;img class=&quot;centered&quot; style=&quot;width: 300px;&quot; alt=&quot;Usual Singleton Lookup&quot; src=&quot;https://www.niceideas.ch/roller2/badtrash/mediaresource/a8688128-c6be-4993-9328-1e8506ca2bc7&quot; /&gt;
&lt;/a&gt;
&lt;/div&gt;
&lt;br&gt;

&lt;p&gt;
With IoC, a container, called lightweight container - as opposed to Java EE craps that are very heavy (and very bad) containers - takes care of instantiating and managing the lifecycle of the components as well as, more importantly, injecting the dependencies in every component.
&lt;/p&gt;

&lt;div class=&quot;centering&quot;&gt;
&lt;a href=&quot;https://www.niceideas.ch/roller2/badtrash/mediaresource/585582be-b4c9-4577-a905-1f8029321f95&quot;&gt;
&lt;img class=&quot;centered&quot; style=&quot;width: 405px;&quot; alt=&quot;IoC injection&quot; src=&quot;https://www.niceideas.ch/roller2/badtrash/mediaresource/585582be-b4c9-4577-a905-1f8029321f95&quot; /&gt;
&lt;/a&gt;
&lt;/div&gt;
&lt;br&gt;


&lt;a name=&quot;sec33&quot;&gt;&lt;/a&gt;
&lt;h3&gt;3.3 Various frameworks&lt;/h3&gt;

&lt;p&gt;
The most important IoC containers today are the following:
&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;The &lt;a href=&quot;https://spring.io/&quot;&gt;Spring Framework&lt;/a&gt;  is an application framework and inversion of control container for the Java platform. The core of spring is really about IoC and components management but nowadays there is a complete ecosystem of tools and side frameworks around spring core aimed at developing web application, ORM concerns, etc.&lt;/li&gt;
&lt;li&gt;The &lt;a href=&quot;http://picocontainer.com/introduction.html&quot;&gt;Pico Container&lt;/a&gt;  is a very lightweight IoC Container and only that. Unlike spring, it is designed to remain small and simple and targets only IoC concerns, nothing else. It is not heavily maintained.&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;http://tapestry.apache.org/&quot;&gt;Apache Tapestry&lt;/a&gt; is an open-source component-oriented Java web application framework conceptually similar to JavaServer Faces and Apache Wicket. It provides IoC concerns in addition to the web application framework.&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;https://github.com/google/guice/wiki/GettingStarted&quot;&gt;Google Guice&lt;/a&gt; is an open source software framework for the Java platform released by Google. It provides support for dependency injection using annotations to configure Java objects.&lt;/li&gt;
&lt;/ul&gt;


&lt;a name=&quot;sec4&quot;&gt;&lt;/a&gt;
&lt;h2&gt;4. SCIF : Simple and Cute IoC Framework &lt;/h2&gt;

&lt;p&gt;
The rest of this article is dedicated to present the implementation of a very simple IoC framework using Javassist, rather as a way to illustrate how easy and straightforward that is with Javassist than for any other reason :-)
&lt;br&gt;
Implementing Dependency Injection is actually a state-of-the-art use case for Javassist and a nice way to present the possibilities and whereabouts of bytecode manipulation.
&lt;br&gt;
We&apos;ll see now how to use Javassist in the light of a concrete use case: the implementation in a little more than 300 lines of code of a lightweight, simple but cute IoC Container: SCIF - Simple and Cute IoC Framework.
&lt;/p&gt;



&lt;a name=&quot;sec41&quot;&gt;&lt;/a&gt;
&lt;h3&gt;4.1 Principle &lt;/h3&gt;

&lt;p&gt;
SCIF - the system we want to build - is an MVP (Minimum Viable Product). We want it to implement &lt;i&gt;Dependency Injection&lt;/i&gt; in its simplest form:
&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Services are managed by the framework and stored in a Service &lt;i&gt;Registry&lt;/i&gt; &lt;/li&gt;
&lt;li&gt;Services should declare the annotation &lt;code&gt;@Service&lt;/code&gt;&lt;li&gt; to be discovered by the framework. The framework searches for services declaring this annotation in the classpath.&lt;/li&gt;
&lt;li&gt;Dependencies are identified in services using the annotation &lt;code&gt;@Resource&lt;/code&gt;. The framework analyze services to discover about their dependencies at runtime.&lt;/li&gt;
&lt;li&gt;If &lt;code&gt;@Resource&lt;/code&gt; is declared on a field, the framework injects the dependency directly, at build time.&lt;/li&gt;
&lt;li&gt;If &lt;code&gt;@Resource&lt;/code&gt; is declared on a getter, the framework uses bytecode manipulation to override the getter in a subclass and implement &lt;i&gt;lazy loading&lt;/i&gt; of the dependency.
&lt;/ul&gt;

&lt;p&gt;
In case of getter (property) injection instead of field injection, SCIF is forced to generate a sub-class of the initial class and override the getter in that sub-class to implement lazy-loading.
&lt;br&gt;
This is a consequence of the usage of an annotation to identify the services to be enhanced: in order for the framework to be able to query the annotation on a class, that class needs unfortunately to be loaded by the Classloader. Javassist is not able to change a class once that class has been loaded (well at least not easily).
&lt;br&gt;
Changing a class that is already loaded leads unusually to a linkage error and that is forbidden without usage of very advanced techniques, too difficult for this simple framework.
&lt;/p&gt;
&lt;p&gt;
&lt;b&gt;Example&lt;/b&gt;
&lt;/p&gt;
&lt;p&gt;
The code below presents a &lt;code&gt;ServiceA&lt;/code&gt; having two dependencies: &lt;code&gt;ServiceB&lt;/code&gt; and &lt;code&gt;ServiceC&lt;/code&gt;.
&lt;br&gt;
The first dependency, &lt;code&gt;ServiceB&lt;/code&gt; is declared by &lt;code&gt;ServiceA&lt;/code&gt; on the field itself, using the annotation &lt;code&gt;@Resource&lt;/code&gt;.
&lt;br&gt;
The second dependency, &lt;code&gt;ServiceC&lt;/code&gt; is declared on the getter, indicating the will of the developer to benefit from lazy loading.
&lt;/p&gt;
&lt;p&gt;
The example below illustrates in &lt;code&gt;&lt;span style=&quot;color: #CB0000;&quot;&gt;red&lt;/span&gt;&lt;/code&gt; the code or behaviour that should be injected at runtime by SCIF.
&lt;/p&gt;

&lt;pre&gt;
&lt;b&gt;import&lt;/b&gt; ch.niceideas.common.service.Registry;
&lt;b&gt;import&lt;/b&gt; ch.niceideas.common.service.Service;
&lt;b&gt;import&lt;/b&gt; javax.annotation.Resource;

&lt;span style=&quot;color: green;&quot;&gt;/** A Business Service  */&lt;/span&gt;
@Service
&lt;b&gt;public class&lt;/b&gt; ServiceA {

    @Resource &lt;span style=&quot;color: green;&quot;&gt;// here we inject the dependency on the field&lt;/span&gt;
    &lt;b&gt;private&lt;/b&gt; ServiceB serviceB = &lt;span style=&quot;color: #CB0000;&quot;&gt;service_injected_by_reflection;&lt;/span&gt;

    &lt;b&gt;private&lt;/b&gt; ServiceC serviceC;

    &lt;b&gt;public&lt;/b&gt; ServiceB getServiceB() { &lt;b&gt;return&lt;/b&gt; serviceB; }
    &lt;b&gt;public void&lt;/b&gt; setServiceB(ServiceB serviceB) { &lt;b&gt;this&lt;/b&gt;.serviceB = serviceB; }

    @Resource &lt;span style=&quot;color: green;&quot;&gt;// here we inject the dependency on the property (getter)&lt;/span&gt;
    &lt;b&gt;public&lt;/b&gt; ServiceC getServiceC() { &lt;b&gt;return&lt;/b&gt; serviceC; }
    &lt;b&gt;public void&lt;/b&gt; setServiceC(ServiceC serviceC) { &lt;b&gt;this&lt;/b&gt;.serviceC = serviceC; }
&lt;span style=&quot;color: #CB0000;&quot;&gt;
    // we want to use javassist to generate a sub-class on the fly, at runtime, to handle
    // the lazy loading of ServiceC at runtime
    &lt;b&gt;public static class&lt;/b&gt; javassist_sub &lt;b&gt;extends&lt;/b&gt; ServiceA {

        &lt;b&gt;private&lt;/b&gt; Registry registry = injected_by_reflection;

        &lt;b&gt;public&lt;/b&gt; ServiceC getServiceC() {
            ServiceC retObject = &lt;b&gt;super&lt;/b&gt;.getServiceC();
            if (retObject == &lt;b&gt;null&lt;/b&gt;) {
                retObject = (ServiceC) registry.getService(
                        ServiceC.&lt;b&gt;class&lt;/b&gt;.getCanonicalName());
                &lt;b&gt;super&lt;/b&gt;.setServiceC(retObject);
            }
            &lt;b&gt;return&lt;/b&gt; retObject;
        }
    }&lt;/span&gt;
}
&lt;/pre&gt;

&lt;p&gt;
Now let&apos;s see what is the design of the SCIF framework enabling this behaviour.
&lt;/p&gt;


&lt;a name=&quot;sec42&quot;&gt;&lt;/a&gt;
&lt;h3&gt;4.2 Design &lt;/h3&gt;

&lt;p&gt;
SCIF is implemented by the following fundamental classes:
&lt;/p&gt;

&lt;ol&gt;

&lt;li&gt;
&lt;code&gt;&lt;b&gt;Registry&lt;/b&gt;&lt;/code&gt; : a Registry is a service manager. It stores services following a specific scope passed to the &lt;code&gt;storeService&lt;/code&gt; method.
&lt;br&gt;
Stored services can be retrieved regardless of the scope. They are searched in the smallest scope first and then in larger scopes.
&lt;/li&gt;

&lt;li&gt;
&lt;code&gt;&lt;b&gt;StaticRegistry&lt;/b&gt;&lt;/code&gt; : a static registry stores services in a static map.
&lt;br&gt;
Only the &lt;code&gt;APPLICATION&lt;/code&gt; scope is supported. Attempting to store a service in another scope results in an exception.
&lt;/li&gt;

&lt;li&gt;
&lt;code&gt;&lt;b&gt;RegistryInitializer&lt;/b&gt;&lt;/code&gt; : the RegistryInitializer is the most important component of SCIF.
&lt;br&gt;
It is responsible for:
&lt;br&gt;
&lt;ul&gt;
&lt;li&gt;Searching the classpath for classes declaring the @Service annotation&lt;/li&gt;
&lt;li&gt;Injecting dependencies in the various form supported by the IoC Framework:
    &lt;ul&gt;
    &lt;li&gt;&lt;b&gt;Field injection&lt;/b&gt;. This is done using simply runtime reflection.&lt;/li&gt;
    &lt;li&gt;&lt;b&gt;Method (getter) injection&lt;/b&gt;. This is done by generating dynamically a subclass that takes care of the
        &lt;i&gt;Lazy Loading&lt;/i&gt; of the dependency.
    &lt;/li&gt;
    &lt;/ul&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;

&lt;li&gt;&lt;code&gt;&lt;b&gt;@Service&lt;/b&gt;&lt;/code&gt; : this annotation identifies services to be searched for in the classpath.&lt;/li&gt;
&lt;li&gt;&lt;code&gt;&lt;b&gt;@Resource&lt;/b&gt;&lt;/code&gt; : this annotation identifies dependencies to be injected either at field level or getter (property) level.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;
The design is as follows:
&lt;/p&gt;

&lt;div class=&quot;centering&quot;&gt;
&lt;a href=&quot;https://www.niceideas.ch/roller2/badtrash/mediaresource/07d50408-4f22-42ae-aed8-f33c15f76b69&quot;&gt;
&lt;img class=&quot;centered&quot; style=&quot;width: 750px;&quot; alt=&quot;SCIF Design&quot; src=&quot;https://www.niceideas.ch/roller2/badtrash/mediaresource/07d50408-4f22-42ae-aed8-f33c15f76b69&quot; /&gt;
&lt;/a&gt;
&lt;/div&gt;
&lt;br&gt;

&lt;p&gt;
&lt;b&gt;Rules regarding &lt;code&gt;@Resource&lt;/code&gt; handling&lt;/b&gt;
&lt;/p&gt;
&lt;p&gt;
The &lt;code&gt;RegistryInitializer&lt;/code&gt; analyzes the classes annotated with &lt;code&gt;@Service&lt;/code&gt; and handles &lt;code&gt;@Resource&lt;/code&gt; annotations the following way:
&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;If &lt;code&gt;@Resource&lt;/code&gt; is declared on a field: in this case there is actually no need for bytecode manipulation. When the &lt;code&gt;RegistryInitializer&lt;/code&gt; analyzes the services, it simply injects the reference to the field.&lt;/li&gt;
&lt;li&gt;If &lt;code&gt;@Resource&lt;/code&gt; is declared on a getter, and a corresponding setter is found: in this case, the system assumes he can use the setter to implement a cache for lazy loading. A subclass is created which overrides the getter to implement lazy loading. When calling the overriden getter, the latest will first call the original getter to see if the result service is already available. If that is the case, that service is returned. if it is not the case, the system will get the target service from the registry and use the corresponding setter to store it before returning it.&lt;/li&gt;
&lt;lI&gt;If &lt;code&gt;@Resource&lt;/code&gt; is declared on arbitrary method or on a getter without a corresponding setter: in this case the system cannot assume he can use the underlying field (through the setter) as a cache, and simply returns the target service from the registry at every call.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;
The &lt;code&gt;RegistryInitializer&lt;/code&gt; uses the following tools / libraries:
&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;code&gt;ReflectionUtils&lt;/code&gt; : a little helper class simplifying some operations related to Runtime Reflection.&lt;/li&gt;
&lt;li&gt;&lt;code&gt;Reflections&lt;/code&gt; (org.reflection.Reflections) : a mandatory package when it comes to analyzing the classpath looking for classes declaring a certain annotation.&lt;/li&gt;
&lt;li&gt;&lt;code&gt;Javassist&lt;/code&gt; : the bytecode manipulation library.&lt;/li&gt;
&lt;/ul&gt;


&lt;a name=&quot;sec43&quot;&gt;&lt;/a&gt;
&lt;h3&gt;4.3 Some focus on code&lt;/h3&gt;

&lt;p&gt;
We&apos;ll see below the most important pieces of code of the SCIF Framework.
&lt;/p&gt;
&lt;p&gt;
(Reminder, &lt;code&gt;&lt;span style=&quot;color: DarkRed&quot;&gt;I am coloring relevant Javassist API calls in dark red&lt;/span&gt;&lt;/code&gt;)
&lt;/p&gt;
&lt;p&gt;
It all starts with the method &lt;code&gt;RegistryInitializer.init()&lt;/code&gt; that takes care of the whole shebang:
&lt;/p&gt;

&lt;pre&gt;
&lt;span style=&quot;color: green;&quot;&gt;/**
 * Initialize a registry from the root package (prefix) given as argument.
 * &amp;lt;br /&gt;
 * The RegistryInitializer will search for classes annotated with @Service and add them 
 * to the returned registry.
 *
 * @param rootPackage
 * @return A Registry containing all discovered services
 * @throws RegistryInitializationException in case of any error
 */&lt;/span&gt;
&lt;b&gt;public static&lt;/b&gt; Registry init(String rootPackage) &lt;b&gt;throws&lt;/b&gt; RegistryInitializationException {

    &lt;b&gt;try&lt;/b&gt; {
        Reflections reflections = &lt;b&gt;new&lt;/b&gt; Reflections(rootPackage);

        Set&amp;lt;Class&amp;lt;?&gt;&gt; annotated = reflections.getTypesAnnotatedWith(Service.class);

        &lt;span style=&quot;color: green;&quot;&gt;// Create service wrappers&lt;/span&gt;
        Map&amp;lt;Class&amp;lt;?&gt;, ServiceWrapper&gt; wrappers = initServiceWrappers(annotated);

        &lt;span style=&quot;color: green;&quot;&gt;// Build set of methods and fields to be analyzed&lt;/span&gt;
        analyzeWrappers(wrappers);

        &lt;span style=&quot;color: green;&quot;&gt;// Now the complicated part, overwrite getters / methods using Javassist,&lt;/span&gt;
        &lt;span style=&quot;color: green;&quot;&gt;// dynamically creating a subclass with bytecode manipulation&lt;/span&gt;
        enhancePropertyGetters(wrappers);

        StaticRegistry registry = &lt;b&gt;new&lt;/b&gt; StaticRegistry();

        &lt;span style=&quot;color: green;&quot;&gt;// Instantiate all the services and store them in Registry 
        // with class name as service name&lt;/span&gt;
        initializeRegistry(wrappers, registry);

        &lt;span style=&quot;color: green;&quot;&gt;// Then do the easy thing : inject service on dependencies expressed on fields&lt;/span&gt;
        proceedFieldInjection(wrappers, registry);

        &lt;b&gt;return&lt;/b&gt; registry;

    } &lt;b&gt;catch&lt;/b&gt; (ReflectiveOperationException | NotFoundException | CannotCompileException e) {
        logger.error (e, e);
        &lt;b&gt;throw&lt;/b&gt; new RegistryInitializationException (e.getMessage(), e);
    }
}
&lt;/pre&gt;

&lt;p&gt;
The really interesting call here is &lt;code&gt;enhancePropertyGetters(wrappers);&lt;/code&gt;. This is where we use bytecode manipulation to generate the subclass dynamically and override the getter of the method declaring the &lt;code&gt;@Resource&lt;/code&gt; annotation.
&lt;br&gt;
We won&apos;t present the other methods but we&apos;ll see the listing of this &lt;code&gt;enhancePropertyGetters()&lt;/code&gt; method:
&lt;/p&gt;

&lt;pre&gt;
&lt;b&gt;private static void&lt;/b&gt; enhancePropertyGetters(Map&amp;lt;Class&amp;lt;?&gt;, ServiceWrapper&gt; wrappers) 
        &lt;b&gt;throws&lt;/b&gt; NotFoundException, CannotCompileException, ClassNotFoundException {
    &lt;span style=&quot;color: DarkRed&quot;&gt;ClassPool.doPruning&lt;/span&gt; = &lt;b&gt;true&lt;/b&gt;;

    &lt;span style=&quot;color: DarkRed&quot;&gt;ClassPool&lt;/span&gt; pool = &lt;span style=&quot;color: DarkRed&quot;&gt;ClassPool.getDefault&lt;/span&gt;();
    pool.&lt;span style=&quot;color: DarkRed&quot;&gt;appendClassPath&lt;/span&gt;(&lt;b&gt;new&lt;/b&gt; &lt;span style=&quot;color: DarkRed&quot;&gt;LoaderClassPath&lt;/span&gt;(
            Thread.currentThread().getContextClassLoader()));

    &lt;b&gt;for&lt;/b&gt; (ServiceWrapper wrapper : wrappers.values()) {

        &lt;b&gt;if&lt;/b&gt; (wrapper.getMethodsToEnhance().size() &gt; &lt;span style=&quot;color: blue;&quot;&gt;0&lt;/span&gt;) {

            &lt;span style=&quot;color: DarkRed&quot;&gt;CtClass&lt;/span&gt; superClazz = pool.&lt;span style=&quot;color: DarkRed&quot;&gt;get&lt;/span&gt;(wrapper.getServiceName());

            &lt;span style=&quot;color: green;&quot;&gt;// Unfortunately I need to go with the sub-class approach
            // I cannot change the original class since it has already been loaded and
            // javassist cannot change a class that is already loaded (that would require
            // changing linking and javassist cannot do that)&lt;/span&gt;

            &lt;span style=&quot;color: DarkRed&quot;&gt;CtClass&lt;/span&gt; clazz = pool.&lt;span style=&quot;color: DarkRed&quot;&gt;makeClass&lt;/span&gt;(wrapper.getServiceName() + &lt;span style=&quot;color: blue;&quot;&gt;&quot;$javassist_sub&quot;&lt;/span&gt;);
            clazz.&lt;span style=&quot;color: DarkRed&quot;&gt;stopPruning&lt;/span&gt;(&lt;b&gt;true&lt;/b&gt;);

            clazz.&lt;span style=&quot;color: DarkRed&quot;&gt;setSuperclass&lt;/span&gt;(superClazz);
            clazz.&lt;span style=&quot;color: DarkRed&quot;&gt;setModifiers&lt;/span&gt;(Modifier.PUBLIC);

            ...

            &lt;span style=&quot;color: green;&quot;&gt;// Add registry on class if not already one. The field might already have been&lt;/span&gt;
            &lt;span style=&quot;color: green;&quot;&gt;// added on a parent class. If this is the case, don&apos;t add it again&lt;/span&gt;
            injectRegistryField(pool, clazz);

            &lt;span style=&quot;color: green;&quot;&gt;// Proceed with method modification&lt;/span&gt;
            &lt;b&gt;for&lt;/b&gt; (Method method : wrapper.getMethodsToEnhance()) {

                &lt;span style=&quot;color: green;&quot;&gt;// Various cases :&lt;/span&gt;

                &lt;span style=&quot;color: green;&quot;&gt;// 1. Method doesn&apos;t have the form of a getter&lt;/span&gt;
                &lt;b&gt;if&lt;/b&gt; (!method.getName().startsWith(&lt;span style=&quot;color: blue;&quot;&gt;&quot;get&quot;&lt;/span&gt;)) {

                    &lt;span style=&quot;color: green;&quot;&gt;// =&gt; Just override method so it returns the service from registry&lt;/span&gt;
                    overrideMethod(clazz, method);
                }

                &lt;span style=&quot;color: green;&quot;&gt;// 2. Method is a getter&lt;/span&gt;
                &lt;b&gt;else&lt;/b&gt; {

                    &lt;b&gt;try&lt;/b&gt; {
                        Method setter = ReflectionUtils.getSetter(wrapper.getServiceClass(),
                                ReflectionUtils.getPropertyName(method),
                                method.getReturnType());

                        &lt;span style=&quot;color: green;&quot;&gt;// 2.2 setter is found
                        // =&gt; Lazy loading : use underlying field as cache.
                        // If it it set, do nothing.
                        // If is is null, look for service and attach it
                        // Needs to override the getter for doing my business and
                        // delegate to the setter for setting the field&lt;/span&gt;
                        overrideGetter(clazz, method, setter);

                    } &lt;b&gt;catch&lt;/b&gt; (NoSuchMethodException e) {

                        logger.debug (e, e);

                        &lt;span style=&quot;color: green;&quot;&gt;// 2.1 No setter could be found&lt;/span&gt;
                        &lt;span style=&quot;color: green;&quot;&gt;// =&gt; Just rewrite method so it returns the service 
                        // from the registry&lt;/span&gt;
                        overrideMethod(clazz, method);
                    }
                }
            }
            
            ...

            &lt;span style=&quot;color: green;&quot;&gt;// make new subclass available to classloader&lt;/span&gt;
            pool.&lt;span style=&quot;color: DarkRed&quot;&gt;toClass&lt;/span&gt;(clazz, Thread.currentThread().getContextClassLoader(), &lt;b&gt;null&lt;/b&gt;);
            clazz.&lt;span style=&quot;color: DarkRed&quot;&gt;stopPruning&lt;/span&gt;(&lt;b&gt;false&lt;/b&gt;);

            &lt;span style=&quot;color: green;&quot;&gt;// use the new subclass instead of the original class from now on&lt;/span&gt;
            Class&amp;lt;?&gt; subClazz = Class.forName(clazz.getName());
            wrapper.overrideClass(subClazz);
        }
    }
}
&lt;/pre&gt;

&lt;p&gt;
In the code above, the interesting calls are &lt;code&gt;overrideGetter()&lt;/code&gt;, &lt;code&gt;overrideMethod()&lt;/code&gt; and &lt;code&gt;injectRegistryField()&lt;/code&gt; since these are the methods where bytecode manipulation occurs.
&lt;br&gt;
Let&apos;s look at these methods:
&lt;/p&gt;

&lt;pre&gt;
&lt;b&gt;private static void&lt;/b&gt; overrideGetter(&lt;span style=&quot;color: DarkRed&quot;&gt;CtClass&lt;/span&gt; clazz, Method getter, Method setter) 
        &lt;b&gt;throws&lt;/b&gt; CannotCompileException {
    String targetService = getter.getReturnType().getCanonicalName();
    &lt;span style=&quot;color: DarkRed&quot;&gt;CtMethod&lt;/span&gt; newMethod = &lt;span style=&quot;color: DarkRed&quot;&gt;CtNewMethod.make&lt;/span&gt;(
                &lt;span style=&quot;color: blue;&quot;&gt;&quot;public &quot;&lt;/span&gt; + targetService + &lt;span style=&quot;color: blue;&quot;&gt;&quot; &quot;&lt;/span&gt; + getter.getName() + &lt;span style=&quot;color: blue;&quot;&gt;&quot;() { \n&quot;&lt;/span&gt; +
                &lt;span style=&quot;color: blue;&quot;&gt;&quot;&quot;&lt;/span&gt; +
                &lt;span style=&quot;color: blue;&quot;&gt;&quot;    &quot;&lt;/span&gt; + targetService + &lt;span style=&quot;color: blue;&quot;&gt;&quot; retObject =  super.&quot;&lt;/span&gt; + getter.getName() + &lt;span style=&quot;color: blue;&quot;&gt;&quot;(); &quot;&lt;/span&gt;+
                &lt;span style=&quot;color: blue;&quot;&gt;&quot;    if (retObject == null) {&quot;&lt;/span&gt; +
                &lt;span style=&quot;color: blue;&quot;&gt;&quot;         retObject =  (&quot;&lt;/span&gt; + targetService + &lt;span style=&quot;color: blue;&quot;&gt;&quot;) \n&quot;&lt;/span&gt; + 
                &lt;span style=&quot;color: blue;&quot;&gt;&quot;                 getRegistry().getService(\&quot;&quot;&lt;/span&gt; + targetService + &lt;span style=&quot;color: blue;&quot;&gt;&quot;\&quot;); &quot;&lt;/span&gt; +
                &lt;span style=&quot;color: blue;&quot;&gt;&quot;         super.&quot;&lt;/span&gt; + setter.getName() + &lt;span style=&quot;color: blue;&quot;&gt;&quot;(retObject);&quot;&lt;/span&gt; +
                &lt;span style=&quot;color: blue;&quot;&gt;&quot;    }&quot;&lt;/span&gt; +
                &lt;span style=&quot;color: blue;&quot;&gt;&quot;    return retObject;&quot;&lt;/span&gt; +
                &lt;span style=&quot;color: blue;&quot;&gt;&quot;&quot;&lt;/span&gt; +
                &lt;span style=&quot;color: blue;&quot;&gt;&quot;}&quot;&lt;/span&gt;,
            clazz);
    clazz.&lt;span style=&quot;color: DarkRed&quot;&gt;addMethod&lt;/span&gt;(newMethod);
}

&lt;b&gt;private static void&lt;/b&gt; overrideMethod(&lt;span style=&quot;color: DarkRed&quot;&gt;CtClass&lt;/span&gt; clazz, Method method) 
        &lt;b&gt;throws&lt;/b&gt; CannotCompileException {
    String targetService = method.getReturnType().getCanonicalName();
    &lt;span style=&quot;color: DarkRed&quot;&gt;CtMethod&lt;/span&gt; newMethod = &lt;span style=&quot;color: DarkRed&quot;&gt;CtNewMethod.make&lt;/span&gt;(
                &lt;span style=&quot;color: blue;&quot;&gt;&quot;public &quot;&lt;/span&gt; + targetService + &lt;span style=&quot;color: blue;&quot;&gt;&quot; &quot;&lt;/span&gt; + method.getName() + &lt;span style=&quot;color: blue;&quot;&gt;&quot;() { \n&quot;&lt;/span&gt; +
                &lt;span style=&quot;color: blue;&quot;&gt;&quot;&quot;&lt;/span&gt; +
                &lt;span style=&quot;color: blue;&quot;&gt;&quot;    &quot;&lt;/span&gt; + targetService + &lt;span style=&quot;color: blue;&quot;&gt;&quot; retObject =  \n&quot;&lt;/span&gt; + 
                &lt;span style=&quot;color: blue;&quot;&gt;&quot;            (&quot;&lt;/span&gt; + targetService + &lt;span style=&quot;color: blue;&quot;&gt;&quot;)\n&quot;&lt;/span&gt; + 
                &lt;span style=&quot;color: blue;&quot;&gt;&quot;            getRegistry().getService(\&quot;&quot;&lt;/span&gt; + targetService + &lt;span style=&quot;color: blue;&quot;&gt;&quot;\&quot;); &quot;&lt;/span&gt; +
                &lt;span style=&quot;color: blue;&quot;&gt;&quot;    return retObject;&quot;&lt;/span&gt; +
                &lt;span style=&quot;color: blue;&quot;&gt;&quot;&quot;&lt;/span&gt; +
                &lt;span style=&quot;color: blue;&quot;&gt;&quot;}&quot;&lt;/span&gt;,
            clazz);
    clazz.&lt;span style=&quot;color: DarkRed&quot;&gt;addMethod&lt;/span&gt;(newMethod);
}

&lt;span style=&quot;color: green;&quot;&gt;/**
 * Inject a field to store the registry in the target clazz as well as a getter 
 * to retrieve that registry.
 *
 * @param pool the Javassist ClassPool to be used
 * @param clazz the class to be modified this way
 * @throws NotFoundException
 * @throws CannotCompileException
 */&lt;/span&gt;
&lt;b&gt;public static void&lt;/b&gt; injectRegistryField(&lt;span style=&quot;color: DarkRed&quot;&gt;ClassPool&lt;/span&gt; pool, &lt;span style=&quot;color: DarkRed&quot;&gt;CtClass&lt;/span&gt; clazz) 
        &lt;b&gt;throws&lt;/b&gt; NotFoundException, CannotCompileException {
    &lt;span style=&quot;color: DarkRed&quot;&gt;CtField&lt;/span&gt; registryField = null;
    &lt;b&gt;try&lt;/b&gt; {
        registryField = clazz.&lt;span style=&quot;color: DarkRed&quot;&gt;getField&lt;/span&gt;(&lt;span style=&quot;color: blue;&quot;&gt;&quot;registry&quot;&lt;/span&gt;);
    } &lt;b&gt;catch&lt;/b&gt; (&lt;span style=&quot;color: DarkRed&quot;&gt;NotFoundException&lt;/span&gt; e) {
        &lt;span style=&quot;color: green;&quot;&gt;// ignored&lt;/span&gt;
    }
    &lt;b&gt;if&lt;/b&gt; (registryField == &lt;b&gt;null&lt;/b&gt;) {
        &lt;span style=&quot;color: DarkRed&quot;&gt;CtClass&lt;/span&gt; registryClass = pool.&lt;span style=&quot;color: DarkRed&quot;&gt;get&lt;/span&gt;(Registry.&lt;b&gt;class&lt;/b&gt;.getName());
        registryField = &lt;b&gt;new&lt;/b&gt; &lt;span style=&quot;color: DarkRed&quot;&gt;CtField&lt;/span&gt;(registryClass, &lt;span style=&quot;color: blue;&quot;&gt;&quot;registry&quot;&lt;/span&gt;, clazz);
        registryField.&lt;span style=&quot;color: DarkRed&quot;&gt;setModifiers&lt;/span&gt;(Modifier.setPrivate(Modifier.STATIC));
        clazz.&lt;span style=&quot;color: DarkRed&quot;&gt;addField&lt;/span&gt;(registryField, &lt;span style=&quot;color: blue;&quot;&gt;&quot;null&quot;&lt;/span&gt;);

        &lt;span style=&quot;color: DarkRed&quot;&gt;CtMethod&lt;/span&gt; registryGetter = &lt;span style=&quot;color: DarkRed&quot;&gt;CtNewMethod.getter&lt;/span&gt;(&lt;span style=&quot;color: blue;&quot;&gt;&quot;getRegistry&quot;&lt;/span&gt;, registryField);
        registryGetter.&lt;span style=&quot;color: DarkRed&quot;&gt;setModifiers&lt;/span&gt;(Modifier.PUBLIC);
        clazz.&lt;span style=&quot;color: DarkRed&quot;&gt;addMethod&lt;/span&gt;(registryGetter);

        &lt;span style=&quot;color: DarkRed&quot;&gt;CtMethod&lt;/span&gt; registrySetter = &lt;span style=&quot;color: DarkRed&quot;&gt;CtNewMethod.make&lt;/span&gt;(
                    &lt;span style=&quot;color: blue;&quot;&gt;&quot;public static void setRegistry (&quot;&lt;/span&gt; + Registry.&lt;b&gt;class&lt;/b&gt;.getName() + 
                    &lt;span style=&quot;color: blue;&quot;&gt;&quot;            holder) { &quot;&lt;/span&gt; +
                    &lt;span style=&quot;color: blue;&quot;&gt;&quot;    registry = holder; &quot;&lt;/span&gt; +
                    &lt;span style=&quot;color: blue;&quot;&gt;&quot;} &quot;&lt;/span&gt;,
                clazz);
        clazz.&lt;span style=&quot;color: DarkRed&quot;&gt;addMethod&lt;/span&gt;(registrySetter);
    }
}
&lt;/pre&gt;

&lt;p&gt;
We&apos;ve seen the most important pieces of code of the SCIF Framework above.
&lt;br&gt;
The framework itself is available for download in the next section.
&lt;/p&gt;

&lt;a name=&quot;sec44&quot;&gt;&lt;/a&gt;
&lt;h3&gt;4.4 DemoApp : Comet Tennis&lt;/h3&gt;

&lt;p&gt;
I integrated the SCIF framework in the comet-tennis demo application. It&apos;s a small application I wrote initially here : &lt;a href=&quot;https://www.niceideas.ch/roller2/badtrash/entry/comet-having-fun-with-the#sec31&quot;&gt;comet-tennis&lt;/a&gt;.
&lt;br&gt;
This application uses a few services and the idea here is to use the SCIF framework to manage these services and inject their dependencies.
&lt;/p&gt;
&lt;p&gt;
The new package with the SCIF framework integrated is available &lt;a download=&quot;comet_tennis_src_0.4.tar.gz&quot; type=&quot;application/tar+gzip&quot; href=&quot;https://www.niceideas.ch/roller2/badtrash/mediaresource/2eeba15c-dc3c-4546-adf8-a41cd4b31932&quot;&gt;here&lt;/a&gt;.
&lt;/p&gt;

&lt;a name=&quot;sec5&quot;&gt;&lt;/a&gt;
&lt;h2&gt;5. Conclusion &lt;/h2&gt;

&lt;p&gt;
Bytecode manipulation is a lot of fun and opens a whole new world of possibilities on the JVM. It&apos;s the only way to implement advanced tooling such as IoC Containers, ORM frameworks, boilerplate code generators, etc.
&lt;br&gt;
Normally, bytecode manipulation is something rather pretty difficult to achieve ... except with Javassist. 
&lt;br&gt;
Javassist makes bytecode manipulation so easy and straightforward. The ability to write dynamically in simple strings actual java source code and add it on the fly as bytecode to classes being manipulated is striking. Javassist is in my opinion the simplest way to perform bytecode manipulation in Java.
&lt;/p&gt;
&lt;p&gt;
I covered &lt;a href=&quot;#sec12&quot;&gt;above&lt;/a&gt; some use cases for bytecode manipulation, there are many others, for instance tampering with licence checking systems of non-free software (Hush. I said nothing)
&lt;/p&gt;
&lt;p&gt;
In my career, I have encountered many situations where I wish afterwards I have known Javassist since it would have been pretty helpful. Let me mention two:
&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
Some 15 years ago, I was working on a pretty big J2EE Websphere application with a lot of EJBS. Tracking the user flow in the distributed system was a nightmare due to the complexity of the business processes and the business rules, so we ended up adding logging information each and every time a business method was entered and left, such as &lt;code&gt;log.debug (&quot;ENTER - business method&quot;)&lt;/code&gt; and &lt;code&gt;log.debug (&quot;LEAVE - business method&quot;)&lt;/code&gt;.
&lt;br&gt;
In regards to troubleshooting, this may sound stupid but it ended up being not only pretty convenient but rather really our single and only way to figure what was going on in some situations in such a enormous software.
&lt;br&gt;
Adding these two lines of code (plus a few &lt;code&gt;try { ... } finally { ... }&lt;/code&gt; statements to make sure the leaving trace was always output made us add thousands of lines of code to the application ... which could have been replaced by a few lines of code java agent and some javassist magic.
&lt;/li&gt;
&lt;li&gt;
Some 10 years ago, I was working for a banking institution on a big Java application making an extensive use of Hibernate. The problem there is that we were trying to map a nice and meaningful business model to a legacy data model. With a lot of hibernate tricks we pretty much succeeded in achieving the mapping, using a lot of custom and pretty tricky code in hibernate session listeners to handle the relationships that hibernate as not able to handle natively.
&lt;br&gt;
There as well, we ended up writing thousands of lines of specific glue code in hibernate listeners which we could have replaced by a pretty simple Javassist base framework to complement the missing features of hibernate.
&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;
You might want to have a look at the second article in this serie available here : &lt;a href=&quot;https://www.niceideas.ch/roller2/badtrash/entry/bytecode-manipulation-with-javassist-for1&quot;&gt;Bytecode manipulation with Javassist for fun and profit part II: Generating toString and getter/setters using bytecode manipulation&lt;/a&gt;.
&lt;/p&gt;
&lt;p&gt;
Part of this article is available as a slideshare presentation here: &lt;a href=&quot;https://www.slideshare.net/JrmeKehrli/bytecode-manipulation-with-javassist-for-fun-and-profit&quot;&gt;https://www.slideshare.net/JrmeKehrli/bytecode-manipulation-with-javassist-for-fun-and-profit&lt;/a&gt;.
&lt;/p&gt;

</description>          </item>
    <item>
    <guid isPermaLink="true">https://www.niceideas.ch/roller2/badtrash/entry/java-create-enum-instances-dynamically</guid>
    <title>Java - Create enum instances dynamically</title>
    <dc:creator>Jerome Kehrli</dc:creator>
    <link>https://www.niceideas.ch/roller2/badtrash/entry/java-create-enum-instances-dynamically</link>
        <pubDate>Sat, 13 Nov 2010 15:08:53 -0500</pubDate>
    <category>Java</category>
    <category>dynamic</category>
    <category>dynamic-enum</category>
    <category>enum</category>
    <category>java</category>
    <atom:summary type="html">&lt;p&gt;
I remember the introduction of the brand new enum type in Java 5 (1.5) was a very exciting announce. However, when I finally switched from 1.4 to 1.5 and actually tried Java&apos;s flavoured enum types, I was a bit disappointed. 
&lt;/p&gt;
&lt;p&gt;
Before that, I was using Josh Bloch&apos;s &quot;Typesafe enum&quot; pattern (effective java) for quite a long time and I didn&apos;t really see what was so much better with the new Java native enum construction. Ok, fine, there was the ability to use enum instances in &lt;code&gt;switch - case&lt;/code&gt; statements which seemed fine, but what else ?
&lt;/p&gt;
&lt;p&gt;
Besides, what I used to find great with the &quot;typesafe enum&quot; pattern is that it could be tricked and changed the way I wanted, for instance to be able to dynamically (at runtime) add enum instances to a specific typesafe enum class. I found it very disappointing not to be able to do the very same thing easily with the native Java enum construction.
&lt;/p&gt;
&lt;p&gt;
And now you might wonder &quot;Why the hell could one ever need to dynamically add enum values ?!?&quot;. You do, right ? Well, let&apos;s imagine this scenario:
&lt;/p&gt;
&lt;p&gt;
You have a specific column in a DB table which contains various codes as values. There are more than hundred different codes actually in use in this column. Related to this, you have a business logic which performs different operations on the rows coming from this table, the actual kind of operation applied on the row depends on the value of this code. So there are chance you end up with a lot of &lt;code&gt;if - elseif&lt;/code&gt; statements checking the actual value of the code.
&lt;br&gt;
I myself am allergic to using string comparison in conditions so I want to be able to map the values from this column to an enum type in Java. This way I can compare enum values instead of strings in my conditions and reduce my dependency on the format of the string value.
&lt;/p&gt;
&lt;p&gt;
Now when there are more than a hundred different possible codes in the DB I really don&apos;t have any intent to define them all manually in my enum type. I want to define only the few I am actually using the Java code and let the system add the other ones dynamically, at runtime, when it (the ORM system or whatever I am using for reading the DB rows) encounters a new value from the DB.
&lt;/p&gt;
&lt;p&gt;
Hence my need for dynamically added enum values.
&lt;/p&gt;
&lt;p&gt;
So recently I faced this need once again and took a few hours to build a little solution which enables one to &lt;b&gt;dynamically add values to a Java enum type&lt;/b&gt;. The solution is the following :
&lt;/p&gt;
</atom:summary>        <description>&lt;!-- Java - Create enum instances dynamically --&gt;

&lt;p&gt;
I remember the introduction of the brand new enum type in Java 5 (1.5) was a very exciting announce. However, when I finally switched from 1.4 to 1.5 and actually tried Java&apos;s flavoured enum types, I was a bit disappointed. 
&lt;/p&gt;
&lt;p&gt;
Before that, I was using Josh Bloch&apos;s &quot;Typesafe enum&quot; pattern (effective java) for quite a long time and I didn&apos;t really see what was so much better with the new Java native enum construction. Ok, fine, there was the ability to use enum instances in &lt;code&gt;switch - case&lt;/code&gt; statements which seemed fine, but what else ?
&lt;/p&gt;
&lt;p&gt;
Besides, what I used to find great with the &quot;typesafe enum&quot; pattern is that it could be tricked and changed the way I wanted, for instance to be able to dynamically (at runtime) add enum instances to a specific typesafe enum class. I found it very disappointing not to be able to do the very same thing easily with the native Java enum construction.
&lt;/p&gt;
&lt;p&gt;
And now you might wonder &quot;Why the hell could one ever need to dynamically add enum values ?!?&quot;. You do, right ? Well, let&apos;s imagine this scenario:
&lt;/p&gt;
&lt;p&gt;
You have a specific column in a DB table which contains various codes as values. There are more than hundred different codes actually in use in this column. Related to this, you have a business logic which performs different operations on the rows coming from this table, the actual kind of operation applied on the row depends on the value of this code. So there are chance you end up with a lot of &lt;code&gt;if - elseif&lt;/code&gt; statements checking the actual value of the code. &lt;br&gt;
I myself am allergic to using string comparison in conditions so I want to be able to map the values from this column to an enum type in Java. This way I can compare enum values instead of strings in my conditions and reduce my dependency on the format of the string value. 
&lt;/p&gt;
&lt;p&gt;
Now when there are more than a hundred different possible codes in the DB I really don&apos;t have any intent to define them all manually in my enum type. I want to define only the few I am actually using the Java code and let the system add the other ones dynamically, at runtime, when it (the ORM system or whatever I am using for reading the DB rows) encounters a new value from the DB.
&lt;/p&gt;
&lt;p&gt;
Hence my need for dynamically added enum values.
&lt;/p&gt;
&lt;p&gt;
So recently I faced this need once again and took a few hours to build a little solution which enables one to &lt;b&gt;dynamically add values to a Java enum type&lt;/b&gt;. The solution is the following :
&lt;/p&gt;
&lt;p&gt;
(Complete code here : &lt;a download=&quot;DynamicEnumTest.java&quot; href=&quot;http://niceideas.ch/roller2/badtrash/mediaresource/fb5a257b-0ba4-4ccd-b7ed-c456b54cdb53&quot; &gt;DynamicEnumTest.java&lt;/a&gt;)
&lt;/p&gt;


&lt;p&gt;
&lt;code&gt;&lt;b&gt;&lt;span style=&quot;color: #7F0055;&quot;&gt;void&lt;/span&gt; addEnum(Class&amp;lt;T&amp;gt; enumType, String enumName)&lt;/b&gt;&lt;/code&gt; 
&lt;/p&gt;
&lt;p&gt;
This method adds an enum instance to the enum type given as argument. The whole method code is presented below. We will first details its behaviour and then present every other method this one is using. 
&lt;/p&gt;
&lt;div style=&quot;border: 1px solid #999999;&quot;&gt;
&lt;code style=&quot;white-space: normal; background-color: transparent; color: #000044;&quot;&gt;
&lt;span style=&quot;color: #3f7f5f;&quot;&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;/**&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;* Add an enum instance to the enum class given as argument&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;* &lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;* @param &amp;lt;T&amp;gt; the type of the enum (implicit)&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;* @param enumType the class of the enum to be modified&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;* @param enumName the name of the new enum instance to be added to the class.&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;*/&lt;/span&gt;&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;@SuppressWarnings(&lt;span style=&quot;color: #2A00FF;&quot;&gt;&quot;unchecked&quot;&lt;/span&gt;)&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span style=&quot;color: #7F0055;&quot;&gt;public static&lt;/span&gt; &amp;lt;T &lt;span style=&quot;color: #7F0055;&quot;&gt;extends&lt;/span&gt; Enum&amp;lt;?&amp;gt;&amp;gt; &lt;span style=&quot;color: #7F0055;&quot;&gt;void&lt;/span&gt; addEnum(Class&amp;lt;T&amp;gt; enumType, String enumName) {&lt;br&gt;
&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span style=&quot;color: #3f7f5f;&quot;&gt;// 0. Sanity checks&lt;/span&gt;&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;if (!Enum.&lt;span style=&quot;color: #7F0055;&quot;&gt;class&lt;/span&gt;.isAssignableFrom(enumType)) {&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span style=&quot;color: #7F0055;&quot;&gt;throw new&lt;/span&gt; RuntimeException(&lt;span style=&quot;color: #2A00FF;&quot;&gt;&quot;class &quot;&lt;/span&gt; + enumType + &lt;span style=&quot;color: #2A00FF;&quot;&gt;&quot; is not an instance of Enum&quot;&lt;/span&gt;);&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;}&lt;br&gt;

&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span style=&quot;color: #3f7f5f;&quot;&gt;// 1. Lookup &quot;$VALUES&quot; holder in enum class and get previous enum instances&lt;/span&gt;&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;Field valuesField = &lt;span style=&quot;color: #7F0055;&quot;&gt;null&lt;/span&gt;;&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;Field[] fields = enumType.getDeclaredFields();&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;for (Field field : fields) {&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;if (field.getName().contains(&lt;span style=&quot;color: #2A00FF;&quot;&gt;&quot;$VALUES&quot;&lt;/span&gt;)) {&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;valuesField = field;&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span style=&quot;color: #7F0055;&quot;&gt;break&lt;/span&gt;;&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;}&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;}&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;AccessibleObject.setAccessible(&lt;span style=&quot;color: #7F0055;&quot;&gt;new&lt;/span&gt; Field[] { valuesField }, &lt;span style=&quot;color: #7F0055;&quot;&gt;true&lt;/span&gt;);&lt;br&gt;
&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;try {&lt;br&gt;
&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span style=&quot;color: #3f7f5f;&quot;&gt;// 2. Copy it&lt;/span&gt;            &lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;T[] previousValues = (T[]) valuesField.get(enumType);&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;List&amp;lt;T&amp;gt; values = &lt;span style=&quot;color: #7F0055;&quot;&gt;new&lt;/span&gt; ArrayList&amp;lt;T&amp;gt;(Arrays.asList(previousValues));&lt;br&gt;
&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span style=&quot;color: #3f7f5f;&quot;&gt;// 3. build new enum&lt;/span&gt;&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;T newValue = (T) makeEnum(enumType, // The target enum class &lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;enumName, &lt;span style=&quot;color: #3f7f5f;&quot;&gt;// THE NEW ENUM INSTANCE TO BE DYNAMICALLY ADDED &lt;/span&gt;&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;values.size(),&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span style=&quot;color: #7F0055;&quot;&gt;new&lt;/span&gt; Class&amp;lt;?&amp;gt;[] {}, &lt;span style=&quot;color: #3f7f5f;&quot;&gt;// can be used to pass values to the enum constuctor&lt;/span&gt;&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span style=&quot;color: #7F0055;&quot;&gt;new&lt;/span&gt; Object[] {}); &lt;span style=&quot;color: #3f7f5f;&quot;&gt;// can be used to pass values to the enum constuctor&lt;/span&gt;&lt;br&gt;
&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span style=&quot;color: #3f7f5f;&quot;&gt;// 4. add new value&lt;/span&gt;&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;values.add(newValue);&lt;br&gt;
&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span style=&quot;color: #3f7f5f;&quot;&gt;// 5. Set new values field&lt;/span&gt;&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;setFailsafeFieldValue(valuesField, &lt;span style=&quot;color: #7F0055;&quot;&gt;null&lt;/span&gt;, &lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;values.toArray((T[]) Array.newInstance(enumType, 0)));&lt;br&gt;
&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span style=&quot;color: #3f7f5f;&quot;&gt;// 6. Clean enum cache&lt;/span&gt;&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;cleanEnumCache(enumType);&lt;br&gt;
&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;} &lt;span style=&quot;color: #7F0055;&quot;&gt;catch&lt;/span&gt; (Exception e) {&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;e.printStackTrace();&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span style=&quot;color: #7F0055;&quot;&gt;throw new&lt;/span&gt; RuntimeException(e.getMessage(), e);&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;}&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;}
&lt;/code&gt;
&lt;/div&gt;
&lt;br&gt;

&lt;ol&gt;
	&lt;li&gt;The enum instances are stored in a static variable of the enum class named &lt;code&gt;$VALUES&lt;/code&gt;. Here we search for this static variable, make it &lt;i&gt;accessible&lt;/i&gt; and keep the reference for further usage.&lt;/li&gt;
	&lt;li&gt;The enum instances contained in the &lt;code&gt;$VALUES&lt;/code&gt; static variable are copied (stored) in another (new) list.
	&lt;li&gt;Then the new enum instance is built using another method named &lt;code&gt;makeEnum&lt;/code&gt; which will be discussed later.
	&lt;li&gt;The new enum instance is added to the new enum list.&lt;/li&gt;
	&lt;li&gt;The new enum instance list (containin the new enum instance) is set to the &lt;code&gt;$VALUES&lt;/code&gt; field, overwriting the previous content.&lt;/li&gt;
	&lt;li&gt;The cleaning of the cache answers to something special and tricky. The problem is that the &lt;code&gt;$VALUES&lt;/code&gt; is purely generated by the compiler. So the static java code located in &lt;code&gt;java.lang.Class&lt;/code&gt; cannot be statically linked to it. Hence it needs to access &lt;code&gt;$VALUES&lt;/code&gt; variable using runtime reflection which is a little costy (compared to static method call linking). Hence the code in &lt;code&gt;java.lang.Class&lt;/code&gt; which needs an access to the enum values makes a copy of them upon first usage in a private instance variable, the enum cache &lt;br&gt;
	Thus, adding the new enum instance in the &lt;code&gt;$VALUES&lt;/code&gt; list is not sufficient, one needs to make sure the &lt;code&gt;java.lang.Class&lt;/code&gt; instance caches are cleared as well.&lt;/li&gt;	
&lt;/ol&gt;

&lt;p&gt;
&lt;code&gt;&lt;b&gt;Object makeEnum(Class&amp;lt;?&amp;gt; enumClass, String value, &lt;span style=&quot;color: #7F0055;&quot;&gt;int&lt;/span&gt; ordinal, Class&amp;lt;?&amp;gt;[] additionalTypes, Object[] additionalValues) &lt;/b&gt;&lt;/code&gt;
&lt;/p&gt;
&lt;p&gt;
This method creates the new enum instance. It takes as argument the class for which to create a new enum instance and the name of the enum instance to create. The ordinal argument is the ordinal value which will be associated to the enum instance. The two last arrays are helpful if on want to add an enum instance to an enum type using constructor arguments to store values bound to the enum instances. The details of the method is as follows :
&lt;/p&gt;

&lt;div style=&quot;border: 1px solid #999999;&quot;&gt;
&lt;code style=&quot;white-space: normal; background-color: transparent; color: #000044;&quot;&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span style=&quot;color: #7F0055;&quot;&gt;private static&lt;/span&gt; Object makeEnum(Class&amp;lt;?&amp;gt; enumClass, String value, &lt;span style=&quot;color: #7F0055;&quot;&gt;int&lt;/span&gt; ordinal, &lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;Class&amp;lt;?&amp;gt;[] additionalTypes, Object[] additionalValues) &lt;span style=&quot;color: #7F0055;&quot;&gt;throws&lt;/span&gt; Exception {&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;Object[] parms = &lt;span style=&quot;color: #7F0055;&quot;&gt;new&lt;/span&gt; Object[additionalValues.length + 2];&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;parms[0] = value;&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;parms[1] = Integer.valueOf(ordinal);&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;System.arraycopy(additionalValues, 0, parms, 2, additionalValues.length);&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span style=&quot;color: #7F0055;&quot;&gt;return&lt;/span&gt; enumClass.cast(getConstructorAccessor(enumClass, additionalTypes).newInstance(parms));&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;}&lt;br&gt;
&lt;/code&gt;
&lt;/div&gt;
&lt;br&gt;

&lt;p&gt;
The &lt;code&gt;makeEnum&lt;/code&gt; method uses another method named &lt;code&gt;getConstructorAccessor&lt;/code&gt; to obtain a reference on the constructor accessor allowing to actually create the new enum instance :
&lt;/p&gt;

&lt;div style=&quot;border: 1px solid #999999;&quot;&gt;
&lt;code style=&quot;white-space: normal; background-color: transparent; color: #000044;&quot;&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span style=&quot;color: #7F0055;&quot;&gt;private static&lt;/span&gt; ConstructorAccessor getConstructorAccessor(Class&amp;lt;?&amp;gt; enumClass, &lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;Class&amp;lt;?&amp;gt;[] additionalParameterTypes) &lt;span style=&quot;color: #7F0055;&quot;&gt;throws&lt;/span&gt; NoSuchMethodException {&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;Class&amp;lt;?&amp;gt;[] parameterTypes = &lt;span style=&quot;color: #7F0055;&quot;&gt;new&lt;/span&gt; Class[additionalParameterTypes.length + 2];&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;parameterTypes[0] = String.&lt;span style=&quot;color: #7F0055;&quot;&gt;class&lt;/span&gt;;&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;parameterTypes[1] = &lt;span style=&quot;color: #7F0055;&quot;&gt;int.class&lt;/span&gt;;&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;System.arraycopy(additionalParameterTypes, 0, &lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;parameterTypes, 2, additionalParameterTypes.length);&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span style=&quot;color: #7F0055;&quot;&gt;return&lt;/span&gt; reflectionFactory.newConstructorAccessor(&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;enumClass.getDeclaredConstructor(parameterTypes));&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;}
&lt;/code&gt;
&lt;/div&gt;
&lt;br&gt;

&lt;p&gt;
&lt;code&gt;&lt;b&gt;setFailsafeFieldValue(Field field, Object target, Object value) &lt;span style=&quot;color: #7F0055;&quot;&gt;throws&lt;/span&gt; NoSuchFieldException, IllegalAccessException &lt;/b&gt;&lt;/code&gt;
&lt;/p&gt;
&lt;p&gt;
This method is a convenient method whose responsibility  is to set the value given as argument to the field given as argument on the target given as argument. This sounds easy yet doing in &lt;i&gt;failsafely&lt;/i&gt; is a little bit more tricky than one could guess :
&lt;/p&gt;

&lt;div style=&quot;border: 1px solid #999999;&quot;&gt;
&lt;code style=&quot;white-space: normal; background-color: transparent; color: #000044;&quot;&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span style=&quot;color: #7F0055;&quot;&gt;private static void&lt;/span&gt; setFailsafeFieldValue(Field field, Object target, Object value)&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; throws NoSuchFieldException, IllegalAccessException {&lt;br&gt;
&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span style=&quot;color: #3f7f5f;&quot;&gt;// let&apos;s make the field accessible&lt;/span&gt;&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;field.setAccessible(&lt;span style=&quot;color: #7F0055;&quot;&gt;true&lt;/span&gt;);&lt;br&gt;
&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span style=&quot;color: #3f7f5f;&quot;&gt;// next we change the modifier in the Field instance to&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;// not be final anymore, thus tricking reflection into&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;// letting us modify the static final field&lt;/span&gt;&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;Field modifiersField = Field.&lt;span style=&quot;color: #7F0055;&quot;&gt;class&lt;/span&gt;.getDeclaredField(&lt;span style=&quot;color: #2A00FF;&quot;&gt;&quot;modifiers&quot;&lt;/span&gt;);&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;modifiersField.setAccessible(&lt;span style=&quot;color: #7F0055;&quot;&gt;true&lt;/span&gt;);&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span style=&quot;color: #7F0055;&quot;&gt;int&lt;/span&gt; modifiers = modifiersField.getInt(field);&lt;br&gt;
&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span style=&quot;color: #3f7f5f;&quot;&gt;// blank out the final bit in the modifiers int&lt;/span&gt;&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;modifiers &amp;= ~Modifier.FINAL;&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;modifiersField.setInt(field, modifiers);&lt;br&gt;
&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;FieldAccessor fa = reflectionFactory.newFieldAccessor(field, false);&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;fa.set(target, value);&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;}&lt;br&gt;
&lt;/code&gt;
&lt;/div&gt;
&lt;br&gt;

&lt;p&gt;
&lt;code&gt;&lt;b&gt;cleanEnumCache(Class&amp;lt;?&amp;gt; enumClass) throws NoSuchFieldException, IllegalAccessException&lt;/b&gt;&lt;/code&gt;
&lt;/p&gt;
&lt;p&gt;
This method clears the &lt;i&gt;enum cache variable&lt;/i&gt; on two different JVM implementations.
&lt;/p&gt;

&lt;div style=&quot;border: 1px solid #999999;&quot;&gt;
&lt;code style=&quot;white-space: normal; background-color: transparent; color: #000044;&quot;&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span style=&quot;color: #7F0055;&quot;&gt;private static void&lt;/span&gt; cleanEnumCache(Class&amp;lt;?&amp;gt; enumClass) &lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span style=&quot;color: #7F0055;&quot;&gt;throws&lt;/span&gt; NoSuchFieldException, IllegalAccessException {&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;blankField(enumClass, &lt;span style=&quot;color: #2A00FF;&quot;&gt;&quot;enumConstantDirectory&quot;&lt;/span&gt;); &lt;span style=&quot;color: #3f7f5f;&quot;&gt;// Sun (Oracle?!?) JDK 1.5/6&lt;/span&gt;&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;blankField(enumClass, &lt;span style=&quot;color: #2A00FF;&quot;&gt;&quot;enumConstants&quot;&lt;/span&gt;); &lt;span style=&quot;color: #3f7f5f;&quot;&gt;// IBM JDK&lt;/span&gt;&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;}&lt;br&gt;
&lt;/code&gt;
&lt;/div&gt;
&lt;br&gt;

&lt;p&gt;
It used the &lt;code&gt;blankField&lt;/code&gt; method to actually blank the target field :
&lt;/p&gt;

&lt;div style=&quot;border: 1px solid #999999;&quot;&gt;
&lt;code style=&quot;white-space: normal; background-color: transparent; color: #000044;&quot;&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span style=&quot;color: #7F0055;&quot;&gt;private static void&lt;/span&gt; blankField(Class&amp;lt;?&amp;gt; enumClass, String fieldName) &lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span style=&quot;color: #7F0055;&quot;&gt;throws&lt;/span&gt; NoSuchFieldException, IllegalAccessException {&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span style=&quot;color: #7F0055;&quot;&gt;for&lt;/span&gt; (Field field : Class.&lt;span style=&quot;color: #7F0055;&quot;&gt;class&lt;/span&gt;.getDeclaredFields()) {&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span style=&quot;color: #7F0055;&quot;&gt;if&lt;/span&gt; (field.getName().contains(fieldName)) {&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;AccessibleObject.setAccessible(&lt;span style=&quot;color: #7F0055;&quot;&gt;new&lt;/span&gt; Field[] { field }, &lt;span style=&quot;color: #7F0055;&quot;&gt;true&lt;/span&gt;);&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;setFailsafeFieldValue(field, enumClass, &lt;span style=&quot;color: #7F0055;&quot;&gt;null&lt;/span&gt;);&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span style=&quot;color: #7F0055;&quot;&gt;break&lt;/span&gt;;&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;}&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;}&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;}&lt;br&gt;
&lt;/code&gt;
&lt;/div&gt;
&lt;br&gt;


&lt;p&gt;
On can test this dynamic enum instance adding system using the following little code snippet:
&lt;/p&gt;

&lt;div style=&quot;border: 1px solid #999999;&quot;&gt;
&lt;code style=&quot;white-space: normal; background-color: transparent; color: #000044;&quot;&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span style=&quot;color: #7F0055;&quot;&gt;private static enum&lt;/span&gt; TestEnum {&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;a,&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;b,&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;c;&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;};&lt;br&gt;
&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span style=&quot;color: #7F0055;&quot;&gt;public static void&lt;/span&gt; main(String[] args) {&lt;br&gt;
&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span style=&quot;color: #3f7f5f;&quot;&gt;// Dynamically add 3 new enum instances d, e, f to TestEnum&lt;/span&gt;&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;addEnum(TestEnum.&lt;span style=&quot;color: #7F0055;&quot;&gt;class&lt;/span&gt; , &lt;span style=&quot;color: #2A00FF;&quot;&gt;&quot;d&quot;&lt;/span&gt;);&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;addEnum(TestEnum.&lt;span style=&quot;color: #7F0055;&quot;&gt;class&lt;/span&gt; , &lt;span style=&quot;color: #2A00FF;&quot;&gt;&quot;e&quot;&lt;/span&gt;);&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;addEnum(TestEnum.&lt;span style=&quot;color: #7F0055;&quot;&gt;class&lt;/span&gt; , &lt;span style=&quot;color: #2A00FF;&quot;&gt;&quot;f&quot;&lt;/span&gt;);&lt;br&gt;
&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span style=&quot;color: #3f7f5f;&quot;&gt;// Run a few tests just to show it works OK. &lt;/span&gt;&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;System.out.println(Arrays.deepToString(TestEnum.values()));&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span style=&quot;color: #3f7f5f;&quot;&gt;// Shows : [a, b, c, d, e, f] &lt;/span&gt;&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;}&lt;br&gt;
&lt;/code&gt;
&lt;/div&gt;
&lt;br&gt;


&lt;p&gt;
The complete code presented in this article is available here : &lt;a download=&quot;DynamicEnumTest.java&quot; href=&quot;http://niceideas.ch/roller2/badtrash/mediaresource/fb5a257b-0ba4-4ccd-b7ed-c456b54cdb53&quot;&gt;DynamicEnumTest.java&lt;/a&gt;
&lt;/p&gt;
&lt;p&gt;
Interestingly, this is a situation where runtime reflection, as limited as it is, is yet sufficient for the few required manipulations involved in this dynamic enum creation feature. It would be interesting to see how a much more powerful mechanism such as &lt;i&gt;javassist&lt;/i&gt; (bytecode manipulation) could make things easier. Maybe I&apos;ll dig into it someday ...
&lt;/p&gt;
&lt;p&gt;
HTH
&lt;/p&gt;
</description>          </item>
    <item>
    <guid isPermaLink="true">https://www.niceideas.ch/roller2/badtrash/entry/java-rocks</guid>
    <title>Java rocks !</title>
    <dc:creator>Jerome Kehrli</dc:creator>
    <link>https://www.niceideas.ch/roller2/badtrash/entry/java-rocks</link>
        <pubDate>Wed, 3 Nov 2010 03:40:36 -0400</pubDate>
    <category>Java</category>
    <category>byte-array</category>
    <category>character-decoding</category>
    <category>character-encoding</category>
    <category>java</category>
    <category>string</category>
    <atom:summary type="html">&lt;p&gt;
I&apos;ve been facing an interesting problem with string manipulation in Java lately at work. The requirement was the following :
&lt;/p&gt;
&lt;p&gt;
We have a field on some screen where the user can type in a comment. The comment can have any length the user wants, absolutely any. Should he want to type in a comment of a million characters, he should be able to do so.
&lt;/p&gt;
&lt;p&gt;
Now the right way to store this comment in a database is using a CLOB, a BLOB or a LONGVARCHAR or whatever feature the database natively provides to do so. Unfortunately that&apos;s not the way it was designed. Due to legacy integration needs, all these advance DB types are prohibited within our application. So the way we have to store the comment consists of using several rows with a single comment field of a maximum length of 500 characters. That means the long comment has to be split in several sub-strings of 500 characters and each of them is stored in a separate row in the DB table. The table has a counter as part of the primary key which is incremented for each new row belonging to the same comment. This way we can easily spot every row part of the same comment.
&lt;/p&gt;
&lt;p&gt;
Now another problem we have is that under DB2 a field defined as &lt;code&gt;VARCHAR(500)&lt;/code&gt; can contain 500 bytes max even though the strings are encoded in UTF-8 in the database. That means we might not be able to store 500 characters if the string contains one or more 2 bytes UTF-8 characters. Working in a french environment, this happens a lot. &lt;br /&gt;
So we had to write a little algorithm taking care of the splitting of the string in 500 bytes sub-strings.
&lt;/p&gt;
&lt;p&gt;
The very first version of our algorithm was quite stupid and ended up in splitting the string in a quite naive way: we converted the string to a byte array following an UTF-8 encoding and split the byte array instead of the string. Then each of the 500 bytes arrays was converted back to a string before being inserted in the database. &lt;br /&gt;
Happily, we figured out quite soon that this doesn&apos;t work as it ends up quite often splitting the string right in the middle of a 2 bytes character. The byte arrays being then converted back to strings, the split 2 bytes character was corrupted and could not be corrected any more.
&lt;/p&gt;
&lt;p&gt;
Before writing as smarter version of the algorithm which would manually test the byte length of the character right at the position of the split, we took a leap backward and wondered : &quot;Can it be that Java doesn&apos;t offer natively a simple way to do just that ?&quot;
&lt;/p&gt;
&lt;p&gt;
And the answer is yes of course. 
&lt;/p&gt;</atom:summary>        <description>&lt;p&gt;
I&apos;ve been facing an interesting problem with string manipulation in Java lately at work. The requirement was the following :
&lt;/p&gt;
&lt;p&gt;
We have a field on some screen where the user can type in a comment. The comment can have any length the user wants, absolutely any. Should he want to type in a comment of a million characters, he should be able to do so.
&lt;/p&gt;
&lt;p&gt;
Now the right way to store this comment in a database is using a CLOB, a BLOB or a LONGVARCHAR or whatever feature the database natively provides to do so. Unfortunately that&apos;s not the way it was designed. Due to legacy integration needs, all these advance DB types are prohibited within our application. So the way we have to store the comment consists of using several rows with a single comment field of a maximum length of 500 characters. That means the long comment has to be split in several sub-strings of 500 characters and each of them is stored in a separate row in the DB table. The table has a counter as part of the primary key which is incremented for each new row belonging to the same comment. This way we can easily spot every row part of the same comment.
&lt;/p&gt;
&lt;p&gt;
Now another problem we have is that under DB2 a field defined as &lt;code&gt;VARCHAR(500)&lt;/code&gt; can contain 500 bytes max even though the strings are encoded in UTF-8 in the database. That means we might not be able to store 500 characters if the string contains one or more 2 bytes UTF-8 characters. Working in a french environment, this happens a lot. &lt;br&gt;
So we had to write a little algorithm taking care of the splitting of the string in 500 bytes sub-strings.
&lt;/p&gt;
&lt;p&gt;
The very first version of our algorithm was quite stupid and ended up in splitting the string in a quite naive way: we converted the string to a byte array following an UTF-8 encoding and split the byte array instead of the string. Then each of the 500 bytes arrays was converted back to a string before being inserted in the database. &lt;br&gt;
Happily, we figured quite soon that this doesn&apos;t work as it ends up quite often splitting the string right in the middle of a 2 bytes character. The byte arrays being then converted back to strings, the split 2 bytes character was corrupted and could not be corrected any more.
&lt;/p&gt;
&lt;p&gt;
Before writing as smarter version of the algorithm which would manually test the byte length of the character right at the position of the split, we took a leap backward and wondered : &quot;Can it be that Java doesn&apos;t offer natively a simple way to do just that ?&quot;
&lt;/p&gt;
&lt;p&gt;
And the answer is yes of course. 
&lt;/p&gt;
&lt;p&gt;
The solution with Java is quite straightforward :
&lt;/p&gt;

&lt;code style=&quot;white-space: normal;&quot;&gt;
&lt;span style=&quot;color: #7F0055;&quot;&gt;import&lt;/span&gt; java.nio.ByteBuffer;&lt;br&gt;
&lt;span style=&quot;color: #7F0055;&quot;&gt;import&lt;/span&gt; java.nio.CharBuffer;&lt;br&gt;
&lt;span style=&quot;color: #7F0055;&quot;&gt;import&lt;/span&gt; java.nio.charset.CharacterCodingException;&lt;br&gt;
&lt;span style=&quot;color: #7F0055;&quot;&gt;import&lt;/span&gt; java.nio.charset.Charset;&lt;br&gt;
&lt;span style=&quot;color: #7F0055;&quot;&gt;import&lt;/span&gt; java.nio.charset.CharsetDecoder;&lt;br&gt;
&lt;span style=&quot;color: #7F0055;&quot;&gt;import&lt;/span&gt; java.nio.charset.CharsetEncoder;&lt;br&gt;
&lt;span style=&quot;color: #7F0055;&quot;&gt;import&lt;/span&gt; java.nio.charset.CoderResult;&lt;br&gt;
&lt;span style=&quot;color: #7F0055;&quot;&gt;import&lt;/span&gt; java.util.ArrayList;&lt;br&gt;
&lt;span style=&quot;color: #7F0055;&quot;&gt;import&lt;/span&gt; java.util.List;&lt;br&gt;
&lt;br&gt;
&lt;span style=&quot;color: #7F0055;&quot;&gt;public class&lt;/span&gt; StringSplitter {&lt;br&gt;
&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span style=&quot;color: #7F0055;&quot;&gt;public static&lt;/span&gt; List&amp;lt;String&amp;gt; splitString500(String value) &lt;span style=&quot;color: #7F0055;&quot;&gt;throws&lt;/span&gt; Exception {&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;List&amp;lt;String&amp;gt; retList = &lt;span style=&quot;color: #7F0055;&quot;&gt;new&lt;/span&gt; ArrayList&amp;lt;String&amp;gt;();&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;try {&lt;br&gt;
&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;Charset utf8CSet = Charset.forName(&lt;span style=&quot;color: #2A00FF;&quot;&gt;&quot;UTF-8&quot;&lt;/span&gt;);&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;CharsetEncoder enc = utf8CSet.newEncoder();&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;CharsetDecoder decoder = utf8CSet.newDecoder();&lt;br&gt;
&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;CharBuffer cBuffer = CharBuffer.wrap(value);&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;ByteBuffer bBuffer = ByteBuffer.allocate(&lt;span style=&quot;color: #2A00FF;&quot;&gt;500&lt;/span&gt;);&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;CoderResult cr = &lt;span style=&quot;color: #7F0055;&quot;&gt;null&lt;/span&gt;;&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span style=&quot;color: #7F0055;&quot;&gt;do&lt;/span&gt; {&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;cr = enc.encode(cBuffer, bBuffer, &lt;span style=&quot;color: #7F0055;&quot;&gt;false&lt;/span&gt;);&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;retList.add(decoder.decode((ByteBuffer) bBuffer.flip()).toString());&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;bBuffer.rewind();&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;} &lt;span style=&quot;color: #7F0055;&quot;&gt;while&lt;/span&gt; (cr != CoderResult.UNDERFLOW);&lt;br&gt;
&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;} &lt;span style=&quot;color: #7F0055;&quot;&gt;catch&lt;/span&gt; (CharacterCodingException e) {&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;e.printStackTrace();&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span style=&quot;color: #7F0055;&quot;&gt;throw new&lt;/span&gt; Exception(e);&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;}&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span style=&quot;color: #7F0055;&quot;&gt;return&lt;/span&gt; retList;&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;}&lt;br&gt;
}&lt;br&gt;
&lt;br&gt;
&lt;/code&gt;

&lt;p&gt;
This piece of code is interesting as it underlines two things :
&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Java is definitely a language making string manipulation as simple as possible. There are hundreds of classes aiming at simplifying the overwhelming complexity of string representation, encoding, decoding, etc. Once again Java rocks.&lt;/li&gt;
&lt;li&gt;Despite working for almost 8 years everyday with Java technologies, I discover new classes and new stuff even in the standard Java libraries everyday, not speaking about the dozens of Java related technologies and libraries that flourish everyday. This is a good example as I was really about to code a piece of code on my own before actually finding out the JDK already provides such a feature. &lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;
Well that was sort of a good lesson of humility. Hackers tend to limit themselves to the set of things they know of the technology and consider everything else just doesn&apos;t exist and has to be done on their own while actually the very feature they are looking for might well already be implemented. One simply need to open his eyes.
&lt;/p&gt;</description>          </item>
    <item>
    <guid isPermaLink="true">https://www.niceideas.ch/roller2/badtrash/entry/communityboard-a-sample-multi-module</guid>
    <title>CommunityBoard : a sample multi-module maven / glassfish / eclipse Java EE project.</title>
    <dc:creator>Jerome Kehrli</dc:creator>
    <link>https://www.niceideas.ch/roller2/badtrash/entry/communityboard-a-sample-multi-module</link>
        <pubDate>Sun, 24 Oct 2010 16:29:13 -0400</pubDate>
    <category>Java</category>
    <category>glassfish</category>
    <category>java2e</category>
    <category>maven</category>
    <category>multi-module</category>
    <category>sample</category>
    <atom:summary type="html">&lt;p&gt;
&lt;i&gt;CommunityBoard&lt;/i&gt; is a sample multi-module maven / glassfish / eclipse Java EE project.
&lt;/p&gt;
&lt;p&gt;
It realizes is a little Forum / Note publishing application. Its main purpose it to act as an 
introducing laboratory to Java EE programming. As such the functionalities are rather limited. Yet it covers the most 
fundamental aspects or issues with Java EE programing in the way it show hows to :
&lt;/p&gt;

&lt;ul&gt;
    &lt;li&gt; write entity beans with bi-directional relationship;&lt;/li&gt;
    &lt;li&gt; use these Entity beans in EJBs (Stateless session beans);&lt;/li&gt;
    &lt;li&gt; use other EJBs in EJBs;&lt;/li&gt;
    &lt;li&gt; use EJBs in a servlet or a JSP located in a WAR (i.e. no processing of the &lt;code&gt;@EJB&lt;/code&gt; annotation);&lt;/li&gt;
    &lt;li&gt; build a multi-module Java EE maven project with jars, wars, ears;&lt;/li&gt;
    &lt;li&gt; how to write JSPs with the JSTL (Ok I am not very proud of these JSPs yet they do the job) and&lt;/li&gt;
    &lt;li&gt; deploy a multi-module ear within Glassfish and use a container defined datasource&lt;/li&gt;
&lt;/ul&gt;
</atom:summary>        <description>&lt;!-- CommunityBoard : a sample multi-module maven / glassfish / eclipse Java EE project. --&gt;
&lt;p&gt;
&lt;i&gt;CommunityBoard&lt;/i&gt; is a sample multi-module maven / glassfish / eclipse Java EE project.
&lt;/p&gt;
&lt;p&gt;
It realizes is a little Forum / Note publishing application. Its main purpose it to act as an 
introducing laboratory to Java EE programming. As such the functionalities are rather limited. Yet it covers the most 
fundamental aspects or issues with Java EE programing in the way it show hows to :
&lt;/p&gt;

&lt;ul&gt;
    &lt;li&gt; write entity beans with bi-directional relationship;&lt;/li&gt;
    &lt;li&gt; use these Entity beans in EJBs (Stateless session beans);&lt;/li&gt;
    &lt;li&gt; use other EJBs in EJBs;&lt;/li&gt;
    &lt;li&gt; use EJBs in a servlet or a JSP located in a WAR (i.e. no processing of the &lt;code&gt;@EJB&lt;/code&gt; annotation);&lt;/li&gt;
    &lt;li&gt; build a multi-module Java EE maven project with jars, wars, ears;&lt;/li&gt;
    &lt;li&gt; how to write JSPs with the JSTL (Ok I am not very proud of these JSPs yet they do the job) and&lt;/li&gt;
    &lt;li&gt; deploy a multi-module ear within Glassfish and use a container defined datasource&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;
The project is available here : &lt;a href=&quot;http://niceideas.ch/community_board.tar.gz&quot;&gt;CommunityBoard.tar.gz&lt;/a&gt;
&lt;/p&gt;

&lt;div class=&quot;centering&quot;&gt;
&lt;h2 class=&quot;centered&quot;&gt;Build and installation instructions&lt;/h2&gt;
&lt;/div&gt;


&lt;h2&gt;1. This document&lt;/h2&gt;

&lt;p&gt;
This document covers the few steps required to build and install the CommunityBoard EAR on a Glassfish 3.0 server and 
presents a very brief manual instruction. The document assumes a basic knowledge of maven command and the Glassfish 3.0 
server.
&lt;/p&gt;
&lt;p&gt;
As a sidenote, one should know the maven pom files provided here make usage of the &lt;code&gt;maven-eclipse-plugin&lt;/code&gt; 
allowing a smooth project integration within eclipse simply by typing &lt;code&gt;mvn eclipse:clean eclipse:eclipse&lt;/code&gt; at 
the root of the project. This command creates the eclipse project files (&lt;code&gt;.project&lt;/code&gt;, &lt;code&gt;.classpath&lt;/code&gt;,
etc.).&lt;br&gt;
This being said, the maven to eclipse project integration won&apos;t be covered any further in this document.
&lt;/p&gt;
&lt;p&gt;
In the same way, this document assumes a basic knowledge of the usual maven commands and the basis of the Glassfish 3.0
Java EE application server on the reader side. We wont cover here the installation of both maven and glassfish and the 
way to use these tools.
&lt;/p&gt;


&lt;h2&gt;2. Some technical information&lt;/h2&gt;


&lt;h3&gt;2.1. The project structure&lt;/h3&gt;

&lt;p&gt;
The project structure is as follows :
&lt;/p&gt;

&lt;table&gt;
    &lt;tr&gt;
        &lt;td&gt;&lt;code&gt;CommunityBoard&lt;/code&gt;&lt;/td&gt; &lt;td&gt;The aggregation module: this one aggregates the 3 other modules to    
             produce a Java EE &lt;i&gt;ear&lt;/i&gt; file containing the 3 other modules.&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
        &lt;td&gt;&lt;code&gt;CommunityBoard_data&lt;/code&gt;&lt;/td&gt; &lt;td&gt;The entity module (data layer). This one is a JPA project which 
             provides the Java EE entity beans used by the project. This modules is packaged as a java &lt;code&gt;.jar&lt;/code&gt; 
             and defined as a &lt;code&gt;jar&lt;/code&gt; module within the aggregation ear.&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
        &lt;td&gt;&lt;code&gt;CommunityBoard_services&lt;/code&gt;&lt;/td&gt; &lt;td&gt;The services module (business layer). This modules provides 
             the various business services used by the CommunityBoard application. This modules is packaged as a java 
             &lt;code&gt;.jar&lt;/code&gt; file on its own and defined as an &lt;code&gt;ejb&lt;/code&gt; module within the aggregation ear.&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
        &lt;td&gt;&lt;code&gt;CommunityBoard_presentation&lt;/code&gt;&lt;/td&gt; &lt;td&gt;The Web module (presentation layer). This modules provides 
             the front controller as well as various JSPs used to present the data and provides the user with ways to 
             manipulate the data. This module is packaged as a java EE &lt;code&gt;.war&lt;/code&gt; file on its own and defined as 
             a &lt;code&gt;web&lt;/code&gt; module within the aggregation ear.&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
        &lt;td&gt;&lt;code&gt;pom.xml&lt;/code&gt;&lt;/td&gt; &lt;td&gt;The root maven POM file.&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
        &lt;td&gt;&lt;code&gt;docs&lt;/code&gt;&lt;/td&gt; &lt;td&gt;A few files (mostly images) used by this README file.&lt;/td&gt;
    &lt;/tr&gt;
&lt;/table&gt;
&lt;br&gt;

&lt;p&gt;
Each individual module is very simple and only holds a few Java files or JSPs as well as its own maven POM file which 
defines the precise way to build it. This documentation won&apos;t cover much more into details the precise content of 
these modules and the author strongly encourage the reader to take a quick look at these modules before going any further 
with the reading of this document.
&lt;/p&gt;

&lt;h3&gt;2.2. The project dependencies&lt;/h3&gt;

&lt;p&gt;
The CommunityBoard project has only 2 dependencies. The snippet of the root maven POM file which defines the dependencies
is:
&lt;/p&gt;

&lt;pre&gt;
        &amp;lt;dependency&amp;gt;
            &amp;lt;groupId&amp;gt;org.apache.derby&amp;lt;/groupId&amp;gt;
            &amp;lt;artifactId&amp;gt;derbyclient&amp;lt;/artifactId&amp;gt;
            &amp;lt;version&amp;gt;10.6.1.0&amp;lt;/version&amp;gt;
        &amp;lt;/dependency&amp;gt;
        &amp;lt;dependency&amp;gt;
            &amp;lt;groupId&amp;gt;javax&amp;lt;/groupId&amp;gt;
            &amp;lt;artifactId&amp;gt;javaee-api&amp;lt;/artifactId&amp;gt;
            &amp;lt;version&amp;gt;6.0-SNAPSHOT&amp;lt;/version&amp;gt;
            &amp;lt;scope&amp;gt;provided&amp;lt;/scope&amp;gt;
        &amp;lt;/dependency&amp;gt;
&lt;/pre&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;b&gt;derbyclient&lt;/b&gt; is the JDBC client to the Glassfish embedded Derby database we will be using.&lt;/li&gt;
  &lt;li&gt;&lt;b&gt;javaee-api&lt;/b&gt; is a required compile time only dependency for pretty much every Java EE project.
&lt;/ul&gt;

&lt;p&gt;
There are actually a few more dependencies such as taglibs for the JSP files. It is however not required to declare these
taglibs in the maven POM file as they are neither required for the maven compilation (JSPs are compiled by the application
server) nor are they required at deployment (both eclipse and glassfish provide them natively).
&lt;/p&gt;

&lt;h2&gt;3. Building and installation&lt;/h2&gt;

&lt;h3&gt;3.1 Build the application&lt;/h3&gt;

&lt;p&gt;
Building the application, thanks to maven, couldn&apos;t be more straightforward. One only needs to &lt;code&gt;cd&lt;/code&gt; into 
the root folder of the project and build the application with the usual maven command :
&lt;/p&gt;

&lt;pre&gt;
user@notebook:/data/.../workspace$ mvn clean install
[INFO] Scanning for projects...
[INFO] Reactor build order: 
[INFO]   Niceideas CommunityBoard project
[INFO]   Niceideas CommunityBoard - data layer
[INFO]   Niceideas CommunityBoard - business layer
[INFO]   Niceideas CommunityBoard - presentation layer
[INFO]   Niceideas CommunityBoard - Agregate EAR
[INFO] ------------------------------------------------------------------------
[INFO] Building Niceideas CommunityBoard project
[INFO]    task-segment: [clean, install]
[INFO] ------------------------------------------------------------------------
...
...
[INFO] 
[INFO] ------------------------------------------------------------------------
[INFO] Reactor Summary:
[INFO] ------------------------------------------------------------------------
[INFO] Niceideas CommunityBoard project ...................... SUCCESS [3.103s]
[INFO] Niceideas CommunityBoard - data layer ................. SUCCESS [6.652s]
[INFO] Niceideas CommunityBoard - business layer ............. SUCCESS [2.206s]
[INFO] Niceideas CommunityBoard - presentation layer ......... SUCCESS [4.780s]
[INFO] Niceideas CommunityBoard - Agregate EAR ............... SUCCESS [1.459s]
[INFO] ------------------------------------------------------------------------
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESSFUL
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 18 seconds
[INFO] Finished at: Sun Oct 24 09:47:18 CEST 2010
[INFO] Final Memory: 28M/119M
[INFO] ------------------------------------------------------------------------
&lt;/pre&gt;

&lt;p&gt;
The above is what should be displayed on the console if the build is successful (really there&apos;s no reason for it not to
be successful).
&lt;/p&gt;
&lt;p&gt;
The build ends up with the project &lt;code&gt;ear&lt;/code&gt; file located at 
&lt;code&gt;./CommunityBoard/target/CommunityBoard-1.0-SNAPSHOT.ear&lt;/code&gt;. This is the file we will be deploying within 
Glassfish.
&lt;/p&gt;

&lt;h3&gt;3.2 Create the datasource&lt;/h3&gt;

&lt;p&gt;
This section and the one below assume the glassfish application server is started and the user/reader has access to the 
administration console. &lt;br&gt;
(&lt;i&gt;Just as a sidenote, glassfish is typically started by : &lt;code&gt;$ glassfish/bin/startserv domain2&lt;/code&gt;&lt;/i&gt;)
&lt;/p&gt;
&lt;p&gt;
In addition to the glassfish application server, the glassfish embedded derby database server should be started as well.
(&lt;i&gt;Just as a sidenote, the embedded derby is typically started by : &lt;code&gt;$ glassfish/bin/asadmin start-database --dbport 1527  --dbhome glassfish/databases&lt;/code&gt;&lt;/i&gt;)
&lt;/p&gt;

&lt;h4&gt;3.2.1 Define the datasource&lt;/h4&gt;

&lt;p&gt;
A datasource named &lt;code&gt;jdbc/CommunityBoardDS&lt;/code&gt; in the JDNI tree is required for the CommunityBoard application to 
work properly. Under glassfish the datasource is easily defined through the admin console by using the 2 links under the 
&lt;i&gt;Resource/jdbc&lt;/i&gt; menu on the left :
&lt;/p&gt;

&lt;div class=&quot;centering&quot;&gt;
&lt;img class=&quot;centered&quot; alt=&quot;glassfish define datasource&quot; src=&quot;https://www.niceideas.ch/roller2/badtrash/mediaresource/fae5139e-c534-4f0b-966b-b3562fe1e129&quot; /&gt;
&lt;/div&gt;
&lt;br&gt;

&lt;p&gt;
First, one should create a new Connection Pool named &lt;code&gt;CommunityBoardPool&lt;/code&gt; for a Derby database. The type of 
the resource is &lt;code&gt;javax.sql.Datasource&lt;/code&gt; :
&lt;/p&gt;


&lt;div class=&quot;centering&quot;&gt;
&lt;img class=&quot;centered&quot; alt=&quot;glassfish define datasource 2&quot; src=&quot;https://www.niceideas.ch/roller2/badtrash/mediaresource/e1bddf60-ef1d-43e1-b146-441db18a8b75&quot; /&gt;
&lt;/div&gt;
&lt;br&gt;

&lt;p&gt;
On the next page, one should go to the bottom of the page and set the connection properties as follows :
&lt;/p&gt;

&lt;div class=&quot;centering&quot;&gt;
&lt;img class=&quot;centered&quot; alt=&quot;glassfish define datasource 3&quot; src=&quot;https://www.niceideas.ch/roller2/badtrash/mediaresource/958efe83-e2b6-4770-adae-4173f7355374&quot; /&gt;
&lt;/div&gt;
&lt;br&gt;

&lt;p&gt;
The mandatory properties are :
&lt;/p&gt;

&lt;div class=&quot;centering&quot;&gt;
&lt;table class=&quot;centered&quot;&gt;
    &lt;tr&gt;
        &lt;td&gt;DatabaseName&lt;/td&gt; &lt;td&gt; &lt;code&gt;CommunityBoard&lt;/code&gt;&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
        &lt;td&gt;User&lt;/td&gt; &lt;td&gt; &lt;code&gt;admin&lt;/code&gt;&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
        &lt;td&gt;Password&lt;/td&gt; &lt;td&gt; &lt;code&gt;whatever&lt;/code&gt;&lt;/td&gt;
    &lt;/tr&gt;
&lt;/table&gt;
&lt;/div&gt;
&lt;br&gt;

&lt;p&gt;
The other properties depend pretty much on your local glassfish installation. In general the embedded derby server
is configured by default as accepting any string as password (hence the &lt;code&gt;whatever&lt;/code&gt; above).
&lt;/p&gt;
&lt;p&gt;
Then one should create a new JDBC resource named &lt;code&gt;jdbc/CommunityBoardDS&lt;/code&gt; and using the provided Derby Pool :
&lt;/p&gt;

&lt;div class=&quot;centering&quot;&gt;
&lt;img class=&quot;centered&quot; alt=&quot;Chosse Derby Pool&quot; src=&quot;https://www.niceideas.ch/roller2/badtrash/mediaresource/1521c1a2-94f6-4053-9fa1-0002463a9bd5&quot; /&gt;
&lt;/div&gt;
&lt;br&gt;

&lt;p&gt;
This is it. The datasource is created an available to deployed applications.
&lt;/p&gt;


&lt;h4&gt;3.2.2 Create the database.&lt;/h4&gt;

&lt;p&gt;
Now the CommunityBoard database should be created. This involves creating the four tables used by the application and 
populating them with initial test data. &lt;br&gt;
The project contains a DDL file located at &lt;code&gt;CommunityBoard_data/src/main/ddl/create_db.sql&lt;/code&gt; and a little SQL 
file containing the test data located at &lt;code&gt;CommunityBoard_data/src/main/ddl/insert_test_data.sql&lt;/code&gt;.
&lt;/p&gt;
&lt;p&gt;
The reader is free to use pretty much any SQL client she is used to. With &lt;i&gt;DBVisualizer&lt;/i&gt; for instance, the SQL 
statements from the SQL files can be easily executed (only one after the other when using the free version of
the tool though). &lt;br&gt;
Under DBVisualizer, the DB connection is defined as follows :
&lt;/p&gt;
&lt;p&gt;
The derby JDBC client driver can be located in the maven local repository once the project has been built at least once.
&lt;/p&gt;

&lt;div class=&quot;centering&quot;&gt;
&lt;img class=&quot;centered&quot; alt=&quot;JDBC Connection in DBVisualizer&quot; src=&quot;https://www.niceideas.ch/roller2/badtrash/mediaresource/683cc69e-7fa6-4162-ace0-287e6364792a&quot; /&gt;
&lt;/div&gt;
&lt;br&gt;

&lt;p&gt;
Please notice that the DDL file should be edited a little bit before usage. It cannot be immediately executed as is, at 
least not without removing first the 4 first lines which contains drop statements in case the script is executed many 
times. These drop statements should be commented out or the script will most likely fail upon execution.
&lt;/p&gt;

&lt;h3&gt;3.3 Deploy the ear&lt;/h3&gt;

&lt;p&gt;
Deploying the ear file built by maven is a piece of cake with glassfish. We&apos;ll use the glassfish admin console here for 
the sake of simplicity.
&lt;/p&gt;
&lt;p&gt;
The ear file to be deployed has been generated by maven in &lt;code&gt;CommunityBoard/target/CommunityBoard.ear&lt;/code&gt;
&lt;/p&gt;
&lt;p&gt;
One only needs to select the &lt;i&gt;Applications&lt;/i&gt; item in the menu on the left and then click on &lt;i&gt;Deploy&lt;/i&gt;. &lt;br&gt;
On the next page, when one selects the ear we have built previously, the admin console fulfills automatically the rest 
of the page :
&lt;/p&gt;

&lt;div class=&quot;centering&quot;&gt;
&lt;img class=&quot;centered&quot; alt=&quot;glassfish deploy ear&quot; src=&quot;https://www.niceideas.ch/roller2/badtrash/mediaresource/e6ea657e-99ec-4819-960c-453fec861f3f&quot; /&gt;
&lt;/div&gt;
&lt;br&gt;

&lt;p&gt;
If everything goes fine, the admin console should display the following page which shows the CommunityBoard application
successfully deployed :
&lt;/p&gt;

&lt;div class=&quot;centering&quot;&gt;
&lt;img class=&quot;centered&quot; alt=&quot;glassfish deploy ear 2&quot; src=&quot;https://www.niceideas.ch/roller2/badtrash/mediaresource/8f0ca557-e2b2-40ea-b707-54f1911ab230&quot; /&gt;
&lt;/div&gt;
&lt;br&gt;

&lt;p&gt;
The user can now reach the following URL with her favorite browser to start using the application : 
&lt;code&gt;http://localhost:8080/CommunityBoard_presentation/controller2/login.do&lt;/code&gt;. 
&lt;/p&gt;
&lt;p&gt;
The test data insertion script should have created a few users, the first one is 
&lt;/p&gt;

&lt;div class=&quot;centering&quot;&gt;
&lt;table class=&quot;centered&quot;&gt;
    &lt;tr&gt;
        &lt;td&gt;Username&lt;/td&gt; &lt;td&gt; &lt;code&gt;user1&lt;/code&gt;&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
        &lt;td&gt;Password&lt;/td&gt; &lt;td&gt; &lt;code&gt;pwd1&lt;/code&gt;&lt;/td&gt;
    &lt;/tr&gt;
&lt;/table&gt;
&lt;/div&gt;
&lt;br&gt;

&lt;p&gt;
which one simply need to type in on the following screen :
&lt;/p&gt;

&lt;div class=&quot;centering&quot;&gt;
&lt;img class=&quot;centered&quot; alt=&quot;CommunityBoard Login&quot; src=&quot;https://www.niceideas.ch/roller2/badtrash/mediaresource/dddfcfca-9406-4cc7-b205-d5c4c1576c95&quot; /&gt;
&lt;/div&gt;
&lt;br&gt; 


&lt;h2&gt;4. A few concerns ...&lt;/h2&gt;

&lt;p&gt;
Just a few concerns :
&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;The JSP are most likely too complicated and a JSP expert would surely be able to do the same or more in twice less 
      lines of code using proper JSP tags. &lt;br&gt;
      Besides, there is the concept of &lt;i&gt;backing bean&lt;/i&gt; which I couldn&apos;t dig very much into details. &lt;br&gt;
      Well, don&apos;t shoot me, I did my best in such a short time.
  &lt;/li&gt;
  &lt;li&gt;I am not yet 100% sure the ServiceLocator used in the web layer to grasp references on EJB&apos;s is required. It&apos;s just
      that I haven&apos;t been able to find a way to make the &lt;code&gt;@EJB&lt;/code&gt; annotation work from within the servlet or the
      JSP pages once I put them and the EJBs in separated projects. &lt;br&gt;
      So I think glassfish just doesn&apos;t take into account a WAR project for annotation processing and hence the 
      ServiceLocator is required. &lt;br&gt;
      (Please don&apos;t hesitate to contact me should you have a better understanding of this issue or a fix to submit for 
      it)
  &lt;/li&gt;
&lt;/ul&gt;

</description>          </item>
    <item>
    <guid isPermaLink="true">https://www.niceideas.ch/roller2/badtrash/entry/dwr-a-paradigm-shift</guid>
    <title>DWR : A paradigm shift in web development</title>
    <dc:creator>Jerome Kehrli</dc:creator>
    <link>https://www.niceideas.ch/roller2/badtrash/entry/dwr-a-paradigm-shift</link>
        <pubDate>Thu, 29 Apr 2010 10:57:58 -0400</pubDate>
    <category>Java</category>
    <category>direct-web-remoting</category>
    <category>dwr</category>
    <category>http</category>
    <category>java</category>
    <category>javascript</category>
    <category>web</category>
    <atom:summary type="html">&lt;p&gt;
I discovered DWR recently and I believe it to be an amazing breakthrough in the world of HTTP client-server comunications.
&lt;/p&gt;
&lt;p&gt;
&lt;b&gt;First what is DWR ?&lt;/b&gt;
&lt;/p&gt;
&lt;p&gt;
DWR stands for &lt;i&gt;&lt;b&gt;D&lt;/b&gt;irect &lt;b&gt;W&lt;/b&gt;eb &lt;b&gt;R&lt;/b&gt;emoting - Easy Ajax for Java&lt;/i&gt;.
&lt;/p&gt;
&lt;p&gt;
DWR is a Java library that enables Java on the server and JavaScript in a browser to interact and call each other as simply as possible. 
&lt;/p&gt;
&lt;p&gt;
Quoting the &lt;a href=&quot;http://directwebremoting.org/dwr/index.html&quot;&gt;official website&lt;/a&gt; :
&lt;/p&gt;
&lt;p&gt;
&lt;i&gt;&quot;DWR is a RPC library which makes it easy to call Java functions from JavaScript and to call JavaScript functions from Java (a.k.a Reverse Ajax).&quot;&lt;/i&gt;&lt;br&gt;
Read this : &lt;a href=&quot;http://directwebremoting.org/dwr/introduction/index.html&quot;&gt;http://directwebremoting.org/dwr/introduction/index.html&lt;/a&gt;.
&lt;/p&gt;</atom:summary>        <description>&lt;!-- DWR : A paradigm shift in web development --&gt;

&lt;p&gt;
I discovered DWR recently and I believe it to be an amazing breakthrough in the world of HTTP client-server comunications.
&lt;/p&gt;
&lt;p&gt;
&lt;b&gt;First what is DWR ?&lt;/b&gt;
&lt;/p&gt;
&lt;p&gt;
DWR stands for &lt;i&gt;&lt;b&gt;D&lt;/b&gt;irect &lt;b&gt;W&lt;/b&gt;eb &lt;b&gt;R&lt;/b&gt;emoting - Easy Ajax for Java&lt;/i&gt;.
&lt;/p&gt;
&lt;p&gt;
DWR is a Java library that enables Java on the server and JavaScript in a browser to interact and call each other as simply as possible. 
&lt;/p&gt;
&lt;p&gt;
Quoting the &lt;a href=&quot;http://directwebremoting.org/dwr/index.html&quot;&gt;official website&lt;/a&gt; :
&lt;/p&gt;
&lt;p&gt;
&lt;i&gt;&quot;DWR is a RPC library which makes it easy to call Java functions from JavaScript and to call JavaScript functions from Java (a.k.a Reverse Ajax).&quot;&lt;/i&gt;&lt;br&gt;
Read this : &lt;a href=&quot;http://directwebremoting.org/dwr/introduction/index.html&quot;&gt;http://directwebremoting.org/dwr/introduction/index.html&lt;/a&gt;.
&lt;/p&gt;
&lt;p&gt;
&lt;b&gt;What&apos;s the point ?&lt;/b&gt;
&lt;/p&gt;
&lt;p&gt;
Yes you can actually call your server-side Java code from within client-side Javascript code just &lt;i&gt;as if &lt;/i&gt;it was in fact some other Javascript code located just aside and definitely not remote code in a foreign technology located on a server far away. Using DWR, you get the illusion your java environment on the server side and the Javascript environment on the client side suddenly and magically got merged together in a single client side Javascript environment.
&lt;/p&gt;
&lt;p&gt;
Even better, using long-poll HTTP requests (recently renamed COMET or Piggy-back HTTP requests or even reverse-AJAX thanks to happy marketing efforts), you can get as close as possible from real server pushes where the Java code running on the server issues RPC-like calls to the client side Javascript code.&lt;br&gt;
Pretty nifty, huh ?
&lt;/p&gt;
&lt;p&gt;
And all of this of course is done (almost completely) transparently. The Javascript code is not aware that the Javascript stub it calls actually forwards the call to some sort of Java server somewhere, no. You can program your client-side Javascript application just as if the server-side business logic actually stands right there on the client-side.
&lt;/p&gt;
&lt;p&gt;
Obviously real-life scenarii suffer from some limitations. For instance, for this to work efficiently, a thorough SOA design is required on both sides to minimize round-trips between the client and the server.
&lt;/p&gt;
&lt;p&gt;
&lt;b&gt;Why is it cool ? &lt;/b&gt;
&lt;/p&gt;
&lt;p&gt;
It&apos;s cool ... because it&apos;s quite obviously cool. Let&apos;s look at the alternatives:
&lt;/p&gt;
&lt;p&gt;
For ages we have been using CGI scripts, then &lt;code&gt;PHP&lt;/code&gt;, then even &lt;code&gt;JSP&lt;/code&gt; or lately &lt;code&gt;JSF&lt;/code&gt; or any other crappy technology alike to build dynamic web applications. I&apos;m sorry fanboys but all of this sucked a lot : complete mixture of concerns and technologies in the same file (some must be thinking this is some sort of good pattern), steady learning curve (got to know HTML, Javascript, CSS, PHP or JAVA, taglibs, etc.), hard to debug, huge network bandwidth consumption (90% of it being presentation stuff, no data), and many other reasons.
&lt;/p&gt;
&lt;p&gt;
Then some smart boys came up with AJAX ... Well &lt;code&gt;XMLHttpRequest&lt;/code&gt; actually is a good thing (although it&apos;s just an easier way to do just the same thing others were doing with hidden iframes since ages). &lt;br&gt;
Anyway, it made (a)synchronous (or at least hidden) server calls easier and enabled client-side Web developers to build Web GUIs acting a little bit more like real GUIs : a single page is loaded, ït builds a GUI and then interacts with the server using artificial, hidden and (a-)synchronous method calls. This definitely was an improvement for two reasons: first it enables a much richer user experience with much more dynamic interfaces where only sub-parts can change and evolve depending on the user interactions. Second, the developer work is made easier as the GUI is built within a single technology, although different languages: Javascript, DOM (HTML) and CSS. &lt;br&gt;
Most of the time, the client-side interface is built using high-level Javascript libraries such as Bindows or DOJO. With such libraries the building of a Web GUI becomes almost as easy as a rich-client GUI.
&lt;/p&gt;
&lt;p&gt;
But let&apos;s face it, there is something with all of this still far from ideal. The problem comes with the &lt;code&gt;&lt;b&gt;XML&lt;/b&gt;&lt;/code&gt; in &lt;code&gt;XMLHttpRequest&lt;/code&gt;. Why the hell should one bother to marshal / unmarshal XML in two different technologies (client-side Javascript and server-side PHP, java, etc.) ? There are cases where Web-services make sense, for instance when a .NET GUI needs to communicate with a Java backend. Both technologies offer several tools to simplify Web-services integration and make them an appropriate choice. &lt;br&gt;
But guys, let&apos;s be honest, this very example really is the only one where Web-services make sense. In every other technology combination, especially within Web application where one side is written in Javascript, there is always a way better alternative to XML. In our case it&apos;s called: &lt;b&gt;JSON&lt;/b&gt;. 
&lt;/p&gt;
&lt;p&gt;
JSON stands for &lt;i&gt;&lt;b&gt;J&lt;/b&gt;avascript &lt;b&gt;S&lt;/b&gt;tandard &lt;b&gt;O&lt;/b&gt;bject &lt;b&gt;N&lt;/b&gt;otation&lt;/i&gt;. Doesn&apos;t it ring a bell ? &lt;br&gt;
Happily, a lot of web developers understand this perfectly nowadays and JSON/RPC is becoming a de-facto standard for cutting-edge modern web developments. The server side backend usually relies on simple &lt;code&gt;REST&lt;/code&gt; services and that is a huge simplification as well over the overwhelming complexity of Web-services.
&lt;/p&gt;
&lt;p&gt;
And this is where DWR kicks in. DWR over-simplifies the complete development process for web application build around REST services and using JSON/RPC as the data exchange format. As I stated before, DWR offers such a high level of abstraction around those REST services that the Web developer really completely ignores every  REST, RPC, marshalling, etc. concerns. She calls the services as if they were plain-old Javascript objects written in Javascript and standing at the client side. &lt;br&gt;
Really cool.
&lt;/p&gt;
&lt;p&gt;
And this is where I believe is the paradigm shift. DWR makes it feel like the client-server separation vanishes. It really feels like everything now stands in one single unified place at the client side.
&lt;/p&gt;
&lt;p&gt;
&lt;b&gt;How does it work ? &lt;/b&gt;
&lt;/p&gt;
&lt;p&gt;
DWR consists of two main parts:
&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;A Java Servlet running on the server that processes requests and sends responses back to the browser.&lt;/li&gt;
&lt;li&gt;JavaScript running in the browser that sends requests and can dynamically update the webpage.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;
DWR works by dynamically generating Javascript based on Java classes. The code does some AJAX magic to make it feel like the execution is happening on the browser, but in reality the server is executing the code and DWR is marshalling the data back and forwards. &lt;br&gt;
DWR used JSON to transmit the data over the network to the server. On the server sides it provides the completely JSON to Plain Old Java Object serialization system.
&lt;/p&gt;
&lt;p&gt;
Every Java object which is intended to be available for remote method calls on the client application should be declared in the &lt;code&gt;dwr.xml&lt;/code&gt; configuration file. DWR then generates the Javascript stubs taking care of the marshalling of the arguments, the remote over HTTP and the unmarshalling of the results. It can be used on a wide range of browser as it supports several way to actually implement the HTTP call: usually using an XMLHttpRequest object, but it can also use hidden iframes in case XMLHttpRequest is not available.
&lt;/p&gt;
&lt;p&gt;
DWR can serialize a complex graph of objects from Javascript to Java and back as well as every sort of collections, exceptions, etc.

&lt;/p&gt;</description>          </item>
    <item>
    <guid isPermaLink="true">https://www.niceideas.ch/roller2/badtrash/entry/hibernate-s-not-found-ignore</guid>
    <title>hibernate&apos;s [not-found=&quot;ignore&quot;] is buggy as hell</title>
    <dc:creator>Jerome Kehrli</dc:creator>
    <link>https://www.niceideas.ch/roller2/badtrash/entry/hibernate-s-not-found-ignore</link>
        <pubDate>Wed, 27 Jan 2010 13:52:36 -0500</pubDate>
    <category>Java</category>
    <category>buggy</category>
    <category>hibernate</category>
    <category>java</category>
    <category>mapping</category>
    <category>not-found</category>
    <atom:summary type="html">&lt;p&gt;
I&apos;m working on a java application which makes an extensive usage of hibernate&apos;s relation mapping system. The later offers several ways to define association mapping. We mostly use &lt;b&gt;&lt;tt&gt;many-to-one&lt;/tt&gt;&lt;/b&gt; relation declarations. The problem comes from the database. It&apos;s a pre-relational, pre-transactional, legacy database running on a prehistorical IBM zSeries host. The data on this database is very often dumb or corrupted. The lack of a proper referential integrity support and the foolish design make us end up quite often following non-existent relations.
&lt;/p&gt;
&lt;p&gt;
Happily, hibernate provides a semantic which allow the application not to bother when a relation is missing, just as the legacy app does. This semantic is the &lt;b&gt;&lt;tt&gt;not-found=&quot;ignore&quot;&lt;/tt&gt;&lt;/b&gt; parameter on the relation definition.
&lt;/p&gt;
&lt;p&gt;
However, the usage of this semantic resumes to open very wide the doors to oblivion.
&lt;/p&gt;</atom:summary>        <description>&lt;!-- hibernate&apos;s &lt;code&gt;not-found=&quot;ignore&quot;&lt;/code&gt; is buggy as hell --&gt;

&lt;p&gt;
I&apos;m working on a java application which makes an extensive usage of hibernate&apos;s relation mapping system. The later offers several ways to define association mapping. We mostly use &lt;code&gt;many-to-one&lt;/code&gt; relation declarations. The problem comes from the database. It&apos;s a pre-relational, pre-transactional, legacy database running on a prehistorical IBM zSeries host. The data on this database is very often dumb or corrupted. The lack of a proper referential integrity support and the foolish design make us end up quite often following non-existent relations.
&lt;/p&gt;
&lt;p&gt;
Happily, hibernate provides a semantic which allow the application not to bother when a relation is missing, just as the legacy app does. This semantic is the &lt;code&gt;not-found=&quot;ignore&quot;&lt;/code&gt; parameter on the relation definition.
&lt;/p&gt;
&lt;p&gt;
However, the usage of this semantic resumes to open very wide the doors to oblivion.
&lt;/p&gt;
&lt;p&gt;
Hibernate&apos;s first level cache is very nifty for what is related to relation management. For instance, it allows great pre-fetching strategies. Should you load a hundred rows from some entity which holds references to another entity, all you have to do is define the relation with &lt;code&gt;lazy=&quot;proxy&quot;&lt;/code&gt; (which is the default), and when you follow one of these relations all the other (for the rest of the hundred rows) are loaded in more or less one shot. &lt;br&gt;
This works great and is very efficient.
&lt;/p&gt;
&lt;p&gt;
Problems arise when the same relation to the very same entity (db table) is mapped using different definitions. We will now illustrate this issue.
&lt;/p&gt;
&lt;p&gt;
&lt;b&gt;Let&apos;s imagine the following situation :&lt;/b&gt;
&lt;/p&gt;

&lt;table style=&quot;border: 1px solid #888888; border-collapse: collapse;&quot;&gt;

&lt;tr&gt;
&lt;td class=&quot;story&quot; style=&quot;width: 80px; border-right: solid 1px #AAAAAA; border-bottom: solid 1px #AAAAAA;&quot;&gt;
&lt;code&gt;&lt;b&gt;Entity C&lt;/b&gt;&lt;/code&gt;
&lt;/td&gt;&lt;td class=&quot;story&quot; style=&quot;text-align: left; border-bottom: solid 1px #AAAAAA;&quot;&gt;
represents the target of both relations
&lt;/td&gt;
&lt;/tr&gt;

&lt;tr&gt;
&lt;td class=&quot;story&quot; style=&quot;width: 80px; border-right: solid 1px #AAAAAA; border-bottom: solid 1px #AAAAAA;&quot;&gt;
&lt;code&gt;&lt;b&gt;Entity A&lt;/b&gt;&lt;/code&gt;
&lt;/td&gt;&lt;td class=&quot;story&quot; style=&quot;text-align: left; border-bottom: solid 1px #AAAAAA;&quot;&gt;
holds a relation to Entity C. The relation is defined with &lt;code&gt;not-found=&quot;exception&quot;&lt;/code&gt; as in the following hibernate mapping file snippet:&lt;br&gt;
&lt;code&gt;&amp;lt;many-to-one name=&quot;associatedC&quot; column=&quot;ID_OF_C&quot; class=&quot;very.nifty.EntityC&quot; lazy=&quot;proxy&quot; not-found=&quot;exception&quot;/&amp;gt;&lt;/code&gt;
&lt;/td&gt;
&lt;/tr&gt;

&lt;tr&gt;
&lt;td class=&quot;story&quot; style=&quot;width: 80px; border-right: solid 1px #AAAAAA; border-bottom: solid 1px #AAAAAA;&quot;&gt;
&lt;code&gt;&lt;b&gt;Entity B&lt;/b&gt;&lt;/code&gt;
&lt;/td&gt;&lt;td class=&quot;story&quot; style=&quot;text-align: left; border-bottom: solid 1px #AAAAAA;&quot;&gt;
holds a relation to Entity C. The relation is defined with &lt;code&gt;not-found=&quot;ignore&quot;&lt;/code&gt; as in the following hibernate mapping file snippet:&lt;br&gt;
&lt;code&gt;&amp;lt;many-to-one name=&quot;associatedC&quot; column=&quot;ID_OF_C&quot; class=&quot;very.nifty.EntityC&quot; not-found=&quot;ignore&quot;/&amp;gt;&lt;/code&gt;
&lt;/td&gt;
&lt;/tr&gt;
&lt;/table&gt;

&lt;p&gt;
This means that both &lt;code&gt;Entity A&lt;/code&gt; and &lt;code&gt;Entity B&lt;/code&gt; hold a relation to &lt;code&gt;Entity C&lt;/code&gt;. All instances of &lt;code&gt;Entity A&lt;/code&gt; should mandatorily have a counterpart target in &lt;code&gt;Entity C&lt;/code&gt;. If none is found following the relation, hibernate should throw an exception.&lt;br&gt;
On the contrary when the target &lt;code&gt;Entity C&lt;/code&gt; corresponding to &lt;code&gt;Entity B&lt;/code&gt; is not found, hibernate should silently set &lt;i&gt;null&lt;/i&gt; on the relation holder and not complain in any way.
&lt;/p&gt;
&lt;p&gt;
We will now see that things can behave quite differently than what we can expect.
&lt;/p&gt;
&lt;p&gt;
&lt;b&gt;Case 1 : only &lt;code&gt;Entity A&lt;/code&gt; instances are loaded.&lt;/b&gt;
&lt;/p&gt;
&lt;p&gt;
When several instances of &lt;code&gt;Entity A&lt;/code&gt; are loaded which reference the same instance of &lt;code&gt;Entity C&lt;/code&gt;, everything works fine. &lt;br&gt;
We have asked hibernate to manage the relation through a proxy. Hence, instances of &lt;code&gt;Entity C&lt;/code&gt; associated to &lt;code&gt;Entity A&lt;/code&gt; are not eagerly fetched. When an instance of &lt;code&gt;Entity A&lt;/code&gt; is build, hibernate associates to it a &lt;i&gt;proxy&lt;/i&gt; on the corresponding &lt;code&gt;Entity C&lt;/code&gt; instance &lt;i&gt;without actually fetching it from the DB&lt;/i&gt;. The proxy is obviously not null. &lt;br&gt;
Only when the program actually tries to call a method on this proxy, hibernate puts the call on hold and tries to load the data from the database. At that stage, if the target &lt;code&gt;Entity C&lt;/code&gt; instance does not exist in the database, hibernate does not have much of a choice but triggers an &lt;code&gt;ObjectNotFoundException&lt;/code&gt;. Due to the proxy already associated to the relation in &lt;code&gt;Entity A&lt;/code&gt;, returning null is not an option any more (obviously). So throwing an exception is pretty much anything hibernate can do.
&lt;/p&gt;
&lt;p&gt;
This works as expected and is fine.
&lt;/p&gt;
&lt;p&gt;
&lt;b&gt;Case 2 : only &lt;code&gt;Entity B&lt;/code&gt; instances are loaded.&lt;/b&gt;
&lt;/p&gt;
&lt;p&gt;
The relation from &lt;code&gt;Entity B&lt;/code&gt; to &lt;code&gt;Entity C&lt;/code&gt; is defined as &lt;code&gt;not-null=&quot;ignore&quot;&lt;/code&gt;. In order to support this, hibernate cannot use any proxing mechanism. It needs to check immediately the existence of the corresponding row in the target table in order to be able to set null on the relation holder within the source entity should the target row not exist. This prevents it from associating a proxy to the relation holder and fetching the row lazily.&lt;br&gt;
You can perfectly define a relation set as &lt;code&gt;not-null=&quot;ignore&quot;&lt;/code&gt; with &lt;code&gt;lazy=&quot;proxy&quot;&lt;/code&gt; but this is just going to be ignored by hibernate. The &lt;code&gt;not-null=&quot;ignore&quot;&lt;/code&gt; primes and the relation is not managed with a proxy.
&lt;/p&gt;
&lt;p&gt;
So what happens if one or several instance of &lt;code&gt;Entity B&lt;/code&gt; are loaded which reference the same instance of &lt;code&gt;Entity C&lt;/code&gt; ? Each and every time an &lt;code&gt;Entity B&lt;/code&gt; is loaded, hibernate will try to find the matching row in &lt;code&gt;Entity C&lt;/code&gt; in the DB. If it doesn&apos;t find it, it will set null to the relation holder in &lt;code&gt;Entity B&lt;/code&gt; and return it to the calling program.
&lt;/p&gt;
&lt;p&gt;
You might think &lt;i&gt;&quot;great, so this &lt;code&gt;not-null=&quot;ignore&quot;&lt;/code&gt; actually works&quot;&lt;/i&gt; and you wouldn&apos;t be wrong. But there&apos;s a trick :
&lt;/p&gt;
&lt;p&gt;
The problem is that the caching mechanisms within hibernate are quite stupid. They don&apos;t cache &lt;b&gt;negative hits&lt;/b&gt;. Imagine you load a hundred rows from &lt;code&gt;Entity B&lt;/code&gt; which all reference the very same row of &lt;code&gt;Entity C&lt;/code&gt; which does not exist. When the first row is loaded, hibernate checks whether the target row in &lt;code&gt;Entity C&lt;/code&gt; exist. It doesn&apos;t and hence hibernate sets null on the first entity relation holder. The the second row is loaded. At that stage hibernate does not remember it already tried to lookup that very same instance of &lt;code&gt;Entity C&lt;/code&gt; and tries again, And again for the third row, and so on. This is quite stupid as there are very few chance that a row suddenly and magically appear between to SQL calls within the same transaction. This might depend of the transaction isolation level of course, but still, chances are very little, especially on very short time periods.&lt;br&gt;
This is what I mean when stating that hibernate does not cache &lt;i&gt;negative hits&lt;/i&gt;. It does not remember that it has already look for some data in a table within a single transaction and that it didn&apos;t find it and it tries again and again and again...Stupid.
&lt;/p&gt;
&lt;p&gt;
However this doesn&apos;t affect the functional behaviour of the application, only the performance, and this is not the problem on which I want to focus here. So let&apos;s be happy with it. And as a sidenote it&apos;s no big deal to fix it on your own in hibernate&apos;s code. One can tweak the first level caching system or the 2nd level cache (a very little bit harder) to cache negative hits as well by using, for instance, a dummy static instance used to identify negative hits.
&lt;/p&gt;
&lt;p&gt;
We&apos;ll know look into a third non-problematic case.
&lt;/p&gt;
&lt;p&gt;
&lt;b&gt;Case 3 : instances of both &lt;code&gt;Entity A&lt;/code&gt; and &lt;code&gt;Entity B&lt;/code&gt; are loaded which reference the same &lt;code&gt;Entity C&lt;/code&gt; instance.&lt;i&gt;&lt;code&gt;Entity B&lt;/code&gt; (with &lt;code&gt;not-found=&quot;ignore&quot;&lt;/code&gt;) loaded first&lt;/i&gt;&lt;/b&gt;
&lt;/p&gt;
&lt;p&gt;
In this case we first load an instance of &lt;code&gt;Entity B&lt;/code&gt;, where the relation is defined with &lt;code&gt;not-found=&quot;ignore&quot;&lt;/code&gt;, and then an instance of &lt;code&gt;Entity A&lt;/code&gt; where the relation is defined with &lt;code&gt;not-found=&quot;exception&quot;&lt;/code&gt; is loaded. Both these two instances reference the very same instance of &lt;code&gt;Entity C&lt;/code&gt;. 
&lt;/p&gt;
&lt;p&gt;
This goes fine. When the instance of &lt;code&gt;Entity B&lt;/code&gt; is loaded, hibernate searches the database for the target instance of &lt;code&gt;Entity C&lt;/code&gt;. It doesn&apos;t exist so hibernate sets null on the relation holder. When the &lt;code&gt;Entity A&lt;/code&gt; is loaded, a proxy for &lt;code&gt;Entity C&lt;/code&gt; is created and associated to it. If one follows the relation on the java object, hibernate doesn&apos;t find the corresponding row and throws an exception, just as expected. 
&lt;/p&gt;
&lt;p&gt;
When further instances of &lt;code&gt;Entity A&lt;/code&gt; or &lt;code&gt;Entity B&lt;/code&gt; are loaded, hibernate still finds a way to behave as expected and associates null values or throws exception when the proxy is accessed, depending on the way the relation has been defined. 
&lt;/p&gt;
&lt;p&gt;
&lt;b&gt;We will now look at the buggy case:&lt;/b&gt;
&lt;/p&gt;
&lt;p&gt;
&lt;b&gt;Case 4 : instances of both &lt;code&gt;Entity A&lt;/code&gt; and &lt;code&gt;Entity B&lt;/code&gt; are loaded which reference the same &lt;code&gt;Entity C&lt;/code&gt; instance.&lt;i&gt;&lt;code&gt;Entity A&lt;/code&gt; (with &lt;code&gt;not-found=&quot;exception&quot;&lt;/code&gt;) loaded first&lt;/i&gt; AND NOT USED.&lt;/b&gt;
&lt;/p&gt;
&lt;p&gt;
Let&apos;s imagine now the following scenario :
&lt;/p&gt;
&lt;p&gt;
We first load an instance of &lt;code&gt;Entity A&lt;/code&gt;, where the relation is defined with &lt;code&gt;not-found=&quot;exception&quot;&lt;/code&gt;, and then an instance of &lt;code&gt;Entity B&lt;/code&gt; where the relation is defined with &lt;code&gt;not-found=&quot;ignore&quot;&lt;/code&gt;. Again, both these two instances reference the very same instance of &lt;code&gt;Entity C&lt;/code&gt;. 
&lt;/p&gt;
&lt;p&gt;
At the time the instance of &lt;code&gt;Entity A&lt;/code&gt; is loaded, the relation is not followed and thus the proxy is not resolved. Hibernate doesn&apos;t know at that stage that the row does not exist.
&lt;/p&gt;
&lt;p&gt;
The problem arises when the instance of &lt;code&gt;Entity B&lt;/code&gt; is loaded. Just as usual, as we have seen before, hibernate should go to the database looking for the target row in order to set null on the relation holder if it doesn&apos;t exist. But for whatever reason, in this very specific case it does not. It gets screwed by the first level cache which keeps a reference on the proxy created for &lt;code&gt;Entity A&lt;/code&gt;.&lt;br&gt;
Instead of looking for the row in the DB and setting null on the relation holder, it finds the proxy in the first level cache and sets it on the relation holder, &lt;b&gt;despite the relation being defined with &lt;code&gt;not-found=&quot;ignore&quot;&lt;/code&gt;&lt;/b&gt;. &lt;br&gt;
The corresponding instance of &lt;code&gt;Entity C&lt;/code&gt; doesn&apos;t exist, but instead of having null on the relation holder, the &lt;code&gt;Entity B&lt;/code&gt; instance has the proxy, which is not null at all !!! &lt;br&gt;
When one tries to follow the relation from &lt;code&gt;Entity B&lt;/code&gt;, hibernate doesn&apos;t have much of a choice but throws an exception, contradicting the &lt;code&gt;not-found=&quot;ignore&quot;&lt;/code&gt; definition.
&lt;/p&gt;
&lt;p&gt;
This happens just always in this very situation. When two objects reference the same third object with different &lt;code&gt;not-found&lt;/code&gt; behaviour, and the one which uses &lt;code&gt;not-found=&quot;exception&quot;&lt;/code&gt; is loaded first, the second gets the same proxy associated to its relation holder and gets screwed when the program tries to follow the relation. The program tests for nullity and gets the proxy, hence not null, and when it tries to call anything on the proxy, it gets an exception. Screwed.
&lt;/p&gt;
&lt;p&gt;
The problem comes from the fact that the entity loading mechanism in hibernate doesn&apos;t keep track of the details of the relation definition when it looks in the first level cache for a relation target. If a proxy exist before any relation defined as &lt;code&gt;not-found=&quot;ignore&quot;&lt;/code&gt; is loaded, the relations will get the proxy from the first level cache, no matter whether the target row exists or not.
&lt;/p&gt;
&lt;p&gt;
The funny thing here is that if any relation defined as &lt;code&gt;not-found=&quot;ignore&quot;&lt;/code&gt; has been loaded first, the problem is not triggered. No matter how the subsequent relations are defined, hibernate finds a way to behave correctly and doesn&apos;t reuse any proxy for relations defined with &lt;code&gt;not-found=&quot;ignore&quot;&lt;/code&gt;. Everything works correctly.&lt;br&gt;
But in the other case, again, is the proxy is created first before any other lookup for the row in the DB, every relation defined with &lt;code&gt;not-found=&quot;ignore&quot;&lt;/code&gt; will be screwed.
&lt;/p&gt;
&lt;p&gt;
&lt;b&gt;So how does one workaround this ?&lt;/b&gt;
&lt;/p&gt;
&lt;p&gt;
Well there&apos;s no silver bullet here. 
&lt;/p&gt;
&lt;p&gt;
The very only solution for this is to make sure every relation which might target a table with missing rows or corrupted references &lt;b&gt;must&lt;/b&gt; declare the relation with &lt;code&gt;not-found=&quot;ignore&quot;&lt;/code&gt; and check programmatically within the Business Object whether this is a problem or not. If it is, the business object throws an exception on his own.
&lt;/p&gt;
&lt;p&gt;
I&apos;m pretty sure this problem has not been experienced by many hibernate users so far as I haven&apos;t been able to find any discussion about it on the various hibernate forums or expert exchange or so. &lt;br&gt;
This makes sense to me as I assume most hibernate users uses it on a modern Database with well defined referential integrity constraints and the whole valuable shebang modern databases can bring to a project. 
&lt;/p&gt;
&lt;p&gt;
But I&apos;m working on a very big project where we have mapped hundred of db tables almost directly in our business object model using hibernate, each of these objects having a lot of relations together and most of them suffering from corrupter references or simply missing rows in the target table.
&lt;/p&gt;
&lt;p&gt;
For us, this problem has been difficult to spot and we are still looking for a better workaround that the one describe above to handle it. If anyone has one, I&apos;m a buyer.
&lt;/p&gt;
&lt;p&gt;
&lt;i&gt;As a sidenote, I cannot provide you here with any test case or program related to this issue as I am experiencing it at work and I have non-divulgation clause linking myself to my employer. And I don&apos;t really have the required time to reproduce it and a specific test case for the moment. &lt;br&gt;
However I might sooner or later open a case for this in the hibernate bug tracking system, so if this problem interests you, you might want to keep looking there sometimes. &lt;/i&gt;

&lt;/p&gt;</description>          </item>
  </channel>
</rss>