When retrieving a column from a ResultSet object using the getObject method, the class is chosen by the JDBC driver. I am looking for a way to choose which class the column is retrieved as at runtime.
In the example below type Class1 is created with variable T as an Integer.
Class Class1<T>
{
public T getColumn(DataSource ds)
{
T value = null;
Connection con = null;
try
{
con = ds.getConnection();
Statement st = con.createStatement();
ResultSet rs = st.executeQuery("select 1 from dual");
rs.next();
Object o = rs.getObject(1); // I want an Integer but a BigDecimal is created!
value = (T) o; // ClassCastException here!
rs.close();
st.close();
}
finally
{
if (con != null) { con.close(); }
}
return i;
}
}
The ResultSet class provides a method called getObject that accepts a column argument and a type Map argument. This type Map is only used for UDT (user defined types). I need this functionality applied to basic SQL types as well. I know I can implement a solution to this using a switch/case statement but I'm trying to avoid that. Is this possible?
EDIT
I should've mentioned I am on Java 1.6. It looks like this may have been solved in 1.7. Thanks JB Nizet for the reference.