[英]JAva:How to pass a custom object type as a parameter to a method and return the same custom object type value back
I am using JDBC template to get my query results from database. 我正在使用JDBC模板从数据库获取查询结果。 I had written the below working code to get my query results converted into the custom object "test" (for which I have a written class for separately).
我已经编写了以下工作代码,以将查询结果转换为自定义对象“ test”(为此我有一个单独的书面类)。
jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<test>(test.class) );
My question is can the above code be made generic/reusable as a method so as to allow any kind of object to be passed as a parameter to this method and return type as the same object as well? 我的问题是,上述代码是否可以作为方法通用/可重用,以便允许将任何类型的对象作为参数传递给此方法,并返回相同对象的类型? Something like the non working code shown as below?
类似于如下所示的无效代码?
public static calledClass ExecuteQuery(String sql,Class calledClass) {
return jdbcTemplate.queryForObject(sqlCommand,new BeanPropertyRowMapper<calledClass>(calledClass.class))
}
In JdbcTemplate
, queryForObject()
is declared as : 在
JdbcTemplate
, queryForObject()
声明为:
public <T> T queryForObject(String sql, RowMapper<T> rowMapper) throws DataAccessException
So, something like that should do the job : 因此,类似的事情应该可以完成工作:
public static <T> T executeQuery(String sql,Class<T> calledClass){
return jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<T>(calledClass));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.