This post originated from an RSS feed registered with Java Buzz
by Brian McCallister.
Original Post: Constructors in Anonymous Inner Classes
Feed Title: Waste of Time
Feed URL: http://kasparov.skife.org/blog/index.rss
Feed Description: A simple waste of time and weblog experiment
A coworker did something that got a good double take today... he put a "constructor" in an anonymous inner class. Java has a nice feature where you can plop down a block anywhere in the class and it gets appended to the constructor, so:
public class Silly {
public Silly() {
System.out.println("1");
}
public void neverCalled() {
System.out.println("Wheeeeeeee!");
}
{
System.out.println("2");
}
}
When instantiated will print 1 and 2. You can additionally set a static block which is executed when the class is initially loaded, but I don't want to think how that will work with anonymous inner classes right now. Anyway, he did this to make sure his anonymous inner class was initialized properly.
It's only January and I think the scary-ass-code-of-the-year award has already been won =)