Wednesday, November 2, 2011

Now this is funky

I wrote something funky today. I was trying to create an instance of an inner-class that was part of my Blah DTO. In Blah, there is a List of Foo objects that needs to be populated based on some logic.

private void populateBlah(Blah var) {

   ...
   Foo foo = var.new Foo();
   ...
}

At first glance, I was baffled at the syntax. I had tried doing the obvious

Foo foo = new Foo();

but Eclipse would have none of it. It threw one of these at me when I tried that

No enclosing instance of type Blah is accessible. Must qualify the allocation with an enclosing instance of type Blah (e.g. x.new A() where x is an instance of Blah).

This still made no sense to me after reading. The Syntax just didn't seem right. I was expecting maybe to create an instance of this perhaps:

Foo foo = new Blah.Foo();

but again, that wasn't the case. Anyway, above is apparently how you instantiate a non-static inner class variable. Who knew. You learn something new every day.

No comments: