简体   繁体   English

JAva:如何将自定义对象类型作为参数传递给方法,并返回相同的自定义对象类型值

[英]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 : JdbcTemplatequeryForObject()声明为:

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.

相关问题 如何为同一方法传递不同的 object 类型,而不是在 java 中编写具有相同功能和返回类型的两个方法 - How to pass different object type for same method instead of writing two methods with same functionality and return type in java 将自定义类对象传递给Java中的泛型类型 - Pass a custom class object to generic type in Java 如何使用自定义Object类为JNI方法定义返回类型? - How to define a return type for a JNI method with a custom Object class? 如何在java中返回Type Custom Bean的空对象? - How to return an empty object of Type Custom Bean in java? java:传递对象并返回相同对象的类型 - java: pass an object and return same object's type java泛型方法的返回类型应该与传递的传递参数相同 - java generics return type of method should be same pass parameter passed 如何将任何对象类型传入方法? 爪哇 - How to pass in any Object type into a method? Java 我可以在春季使用afterThrowing()方法返回自定义类型的对象吗? - Can I return an Object of custom type using afterThrowing() method in spring? Java - 如何将方法的返回类型作为参数传递? - Java - How do I pass the return type of a method as parameter? Soap Web服务未发布为Java中的“自定义对象”返回类型 - Soap web service not getting published for Custom Object return type in Java
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM