I recently ran across the following snippet in an existing codebase I’m working on and added the comment you see there. I know this particular piece of code can be rewritten to be cleaner, but I just wonder if my analysis is correct.
Will java create a new class declaration and store it in perm gen space for every call of this method, or will it know to reuse an existing declaration?
protected List<Object> extractParams(HibernateObjectColumn column, String stringVal) {
// FIXME: could be creating a *lot* of anonymous classes which wastes perm-gen space right?
return new ArrayList<Object>() {
{
add("");
}
};
}
The class will only be compiled once (at compile time). The compiler extracts a class (named something like
MyOuterClass$1) and uses it. It will create multiple instances, of course, but they will all be of the same class. You can see that when you compile the.javafile and look at the.classfiles generated – there will be one for the inner anonymous class.