Monday, December 10, 2012

Named inner classes in methods

Do you know the feeling when you write something that should totally be wrong and it turns out perfectly ok? Well that's what I just experienced: A "WTF?! This is really cool" moment. What gives?

I've been entertaining myself with a little bit of Spring Data exercise. Trying to understand how much will I gain from using JdbcTemplate I dug a little into the sources of that class. At one point I saw that there's a named class (not an anonymous one) declared inside a method. WTF?

I know if I say it like that it is kind of lame of me not to know this. But this is such a nice feature I can't really understand why it's being used so rarely...
public String getName(String user) {
    JdbcTemplate template = new JdbcTemplate(this.datasource);

    class NameExtractor implements ResultSetExtractor {
        @Override
        public String extractData(ResultSet rs) 
            throws SQLException, DataAccessException {
            return rs.getString("firstName") + " " + rs.getString("lastName");
        }
    }

    return template.query("SELECT * FROM users WHERE id=1", new NameExtractor());
}
I know there's like a ton of different ways of writing that code but I have chosen this simple example to show you (and me in a couple of weeks maybe) that inner classes don't need to be defined on class levels.

Have fun!

1 comment:

Matthias Hryniszak said...

Obviously this wouldn't need to exists had Java finally had proper syntax and support for closures..