简体   繁体   中英

Class.getMethod when parameter is varargs

I need to call Class.getMethod(java.lang.String, java.lang.Class...) to get a method where one of the varargs parameters is a varargs.

Currently I'm trying:

// to get jdbcTemplate.queryForObject(RowMapper, Object...)
jdbcTemplate.getClass().getMethod("queryForObject", RowMapper.class, Object.class);

Which results, not surprisingly in

Caused by: java.lang.NoSuchMethodException: org.springframework.jdbc.core.simple.SimpleJdbcTemplate.queryForObject(java.lang.String,     org.springframework.jdbc.core.RowMapper, java.lang.Object)
at java.lang.Class.throwNoSuchMethodException(Class.java:283)
at java.lang.Class.getMethod(Class.java:825)

How can I do this?

You need to provide an array type instead:

getMethod("queryForObject", RowMapper.class, Object[].class);

Basically a varargs parameter is an array, just with an extra bit of metadata telling the compiler to allow that array to be specified as a sequence of elements instead of a single expression.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM