Neat Spring Trick
I don't think this trick is common knowledge because Google doesn't appear to have any reference to it, so maybe it's new to you.
Void
(with a capital V) is a valid type in Java (actually this is Java in general not just Spring). Pre Java 5 I'm not sure it was of any at all, but with generics it can be.
Normally you would use void
(small v) as a return type to say "nothing is returned". There was nothing to stop you returning Void
(big V), but the compiler would insist on you specifically returning nothing using return null;
, so there wasn't much point.
Generics demand Objects and not native types, so Void
(big V) can be useful to say "a collection of nothing", and the context where I found a use for this is Spring 2's JDBC templates.
A few times I've been using Spring's JdbcTemplate
, or specifically here SimpleJdbcTemplate
, and wanted to create some objects and put them in a Set or a Map. This is what SimpleJdbcTemplate.query()
was designed for, except that it only works with Lists. So you alter a Set (or Map etc) defined elsewhere, and then .query()
returns a List<Void>
.
So you can use this trick:
final Set<Page> data = new HashSet<Page>(); jt.query("SELECT ...", new ParameterizedRowMapper<Void>() { public Void mapRow(ResultSet rs, int rowNum) throws SQLException { Page page = new Page(rs.getString(1)); data.add(page); return null; } });
ParameterizedRowMapper requires a type to work with, but you don't want to give it one, because (in the example above) you are filling the Set yourself. So you can use the Void type. The Void type has only one valid value as far as I am aware: null.
So here's a request for the Compiler folks at Sun: Allow methods that return Void (big V) to skip the "return null;
" as you do for methods that return void (small v).
Comments
Comments have been turned off on old posts