I can't get to work java reflection in Spring boot with Controller and JdbcTemplate.
Default controller looks like:
public class DefaultController {
private static final Logger logger = LoggerFactory.getLogger(DefaultController.class);
public JsonResponseDataModel selectOneAuto(Long id, Class<?> repository, HttpServletResponse response){
final JsonResponseDataModel result = new JsonResponseDataModel();
System.out.println("The name of class is " + repository.getName());
Method[] methods = repository.getMethods();
for (Method method : methods) {
System.out.println("Method: " + method.getName());
}
try {
//Method method = repository.getClass().getMethod("selectOne", Long.class);
Method method = repository.getClass().getDeclaredMethod("selectOne", Long.class);
method.invoke(repository, id);
logger.info("selectOneAuto : id={} ", id);
} catch (EmptyResultDataAccessException e) {
result.setEmptyResultDataAccessException("id", id.toString());
} catch (DataAccessException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
return result;
}
}
Inside CompanyRepository class is defined selectOne method with Long input:
@Transactional(readOnly=true)
public CompanyModel selectOne(Long id) {
CompanyModel result = null;
final String sql = "SELECT * FROM company WHERE id=?";
return jdbcTemplate.queryForObject(sql, new Object[]{id}, new CompanyRowMapper());
}
When I create a new class "CompanyController extends DefaultController" and call method selectOneAuto:
selectOneAuto(id, new CompanyRepository().getClass(), response);
Then it ends with error on line "Method method = repository.getClass().getDeclaredMethod("selectOne", Long.class);"
"Java.lang.NoSuchMethodException: java.lang.Class.selectOne(java.lang.Long)"
But the for loop inside "selectOneAuto" method outputs method named "selectOne". What is wrong here?
Aucun commentaire:
Enregistrer un commentaire