Code Obfuscation: Anonymous Inner Class Death

Java, like most other modern languages, will let you get away with some really ugly code. Inspired by my recent gaze into GWT generated JavaScript, I decided to crank out this little gem. I’ve pretty formatted it here because it doesn’t need any assistance to confuse from lack of white space. See if you can figure out what it does and, more importantly, how it does it.

new Object() {
    public void eval(int i) {
      if (new Object() {
            public boolean eval(int i) {
              return i == new Object() {
                  public int getSomeNumber() {
                    return 1000;
                  }
                }.getSomeNumber();
            }
          }.eval(i))
        return;
      System.out.println(String.format("%c", i));
      this.eval(new Object() {
            public int next(int i) {
              return i + new Object() {
                  public int leap() {
                    return 1;
                  }
                }.leap();
            }
          }.next(i));
    }
  }.eval(0);

Take a moment and really drink this in. Its fairly simple to obfuscate just about any simple algorithm using this terrible approach. I don’t even want to think about what this is doing to the JVM’s memory, let alone mine.

GWT can be Magical

The person or people responsible for the following must either be much more knowledgeable than I about JavaScript if statements, or simply more sinister. While pretty compiling one of my GWT modules today, I decided to take a peek at the generated source. As I was scrolling through the the module, my coworker pointed something out. This is what I found:

    if (function(){
      return ua.indexOf('msie') != -1 && $doc_0.documentMode >= 8;
    }
    ())
      return 'ie8';
    if (function(){
      var result = /msie ([0-9]+)\.([0-9]+)/.exec(ua);
      if (result && result.length == 3)
        return makeVersion(result) >= 6000;
    }
    ())
      return 'ie6';

After a few moments with a baffled expression on my face, he made the announcement that he would henceforth be performing all conditional expression evaluations within anonymous functions. I couldn’t agree more. I mean, what better way to mess with the person who will be reviewing, or worse yet, supporting your code? Now, I see what they did there in the IE 6 test. Quite the cleaver hack. Kinda. But to use the same mechanism for the IE8 test is just plain strange. Does anyone have a reason why this pattern might be desirable? I’ve since taken an oath to refrain from examining the generated crap, no matter how pretty it may proclaim to be, until I’ve come a bit further in my GWT mastery.