Wednesday 5 October 2011

Constructor in Anonymous Inner Class

Recently, I've been playing with JMockit, and I've come across certain language constructs in java that confused me.

It appears they were related to creating a different body for a constructor in the inner anonymous class. Which is hard to do, as the name of the Anonymous Inner Class is unknown.

package mrbean.anonymous;

public class Anonymous 
{

  private int i = 5;

  public int getI() 
  {
    System.out.println(this + " getI");
    return i;
  }

  public void setI(int i) 
  {
    System.out.println(this + " setI");
    this.i = i;
  }

  public Anonymous() 
  {
    System.out.println(this + " Constructor");
  }

  public void doStuff() 
  {
    System.out.println(this + " doStuff");
    System.out.println("i=" + new Anonymous() {
      {
        System.out.println(this + " Anonymous Constructor");
        setI(10);
      }
    }.getI());
  }

  /**
   * Main method to start the program.
   * @param args arguments
   */

  public static void main(String[] args) 
  {
    System.out.println("main: Start program.");
    Anonymous first = new Anonymous();
    System.out.println("main: i=" + first.getI());
    first.doStuff();
    System.out.println("main: End program.");
  }

}

This provided me with the following output:

main: Start program.
mrbear.anonymous.Anonymous@7d8a992f Constructor
mrbear.anonymous.Anonymous@7d8a992f getI
main: i=5
mrbear.anonymous.Anonymous@7d8a992f doStuff
mrbear.anonymous.Anonymous$1@23fc4bec Constructor
mrbear.anonymous.Anonymous$1@23fc4bec Anonymous Constructor
mrbear.anonymous.Anonymous$1@23fc4bec setI
mrbear.anonymous.Anonymous$1@23fc4bec getI
i=10
main: End program.

Especially in the creation of Expectations and Verifications in test methods in JMockit, it's quite common.

No comments:

Post a Comment