A blog about software development and other software related matters

Blog Archive

Monday, August 20, 2007

Generics shall risen again!

Here is a possible solution for cases in which some libraries that you depend upon and are not under your control (Spring, Apache Commons etc..) don't use generics (usually this is due to 1.42 backward compatibility), in such cases you'd usually write lines that might resemble something like this:

JdbcTemplate jdbcTemplate=new JdbcTemplate();
List⟨String⟩ result=jdbcTemplate.queryForList(/*query*/,/*params*/);

This code will result in unchecked assignment warning during compilation however the most annoying thing about it is that the IDE will not auto complete the generics types for us(=> more typing for us!).
My solution is based upon JRetrofit a framework that enables us to add interfaces to classes during runtime, first will create an interface that should contain all the commonly used JdbcTemplate methods:

public interface JdbcDynamicWrapper {
 List queryForList(String sql,Object[] args)throws DataAccessException;

And a factory method that will be used to get jdbcTemplate instances:

class JdbcTemplateFactory {
 public ⟨T⟩ JdbcDynamicWrapper⟨T⟩ getTemplateWraper(Class⟨T⟩ clazz){
  JdbcTemplate jdbcTemplate = new JdbcTemplate();

All that is left is to use the factory method:

JdbcTemplateFactory jdbcTemplateFactory=new JdbcTemplateFactory();
List⟩String⟨ names=templateWraper.queryForList(/*query*/,/*params*/);

Now i know that this solution has its down sides (the need to add each method to the interface is one of them), but for methods which are very commonly used i think that its worth its price, don't you?

No comments: