简体   繁体   中英

Calling a method with an generic parameter with Java reflection

I need to call this method : public T unwrap(Class iface) from a class that I can't import.

I'm trying to do this :

 Class jbossWrappedSt = Class.forName("org.jboss.jca.adapters.jdbc.jdk6.WrappedPreparedStatementJDK6");

 Method metodoUnwrap = jbossWrappedSt.getDeclaredMethod ("unwrap", new Class[]{Class.class});
 Object val = metodoUnwrap.invoke (st, new Object[] {PreparedStatement.class});

But fails with a NoSuchMethodException exception:

java.lang.NoSuchMethodException: org.jboss.jca.adapters.jdbc.jdk6.WrappedPreparedStatementJDK6.unwrap(java.lang.Class)

Class javadoc : https://repository.jboss.org/nexus/content/unzip/unzip/org/jboss/ironjacamar/jdbc-local/1.0.28.Final/jdbc-local-1.0.28.Final-javadoc.jar-unzip/org/jboss/jca/adapters/jdbc/JBossWrapper.html#unwrap%28java.lang.Class%29

Update : I forgot to say that we are using Java 1.5 (Yeah! I know).

You are asking for a declared method which precludes the possibility to receive an inherited method. So if WrappedPreparedStatementJDK6 inherits the method from JBossWrapper or some other class in the class hierarchy instead of declaring it itself, the lookup will fail. You should use getMethod which will provide you the method regardless of where in the class hierarchy it is defined, provided the method is public which is the case here.

Nevertheless, since it's defined in standard Java API Wrapper interface , there is no need to use Reflection at all. If the compile-time type of st is not already PreparedStatement , you can simply invoke ((Wrapper)st).unwrap(PreparedStatement.class) .

The class in the Javadoc is

org.jboss.jca.adapters.jdbc.JBossWrapper

however the class you are looking at is a different class.

The class you are look at doesn't have an unwrap method.

https://repository.jboss.org/nexus/content/unzip/unzip/org/jboss/ironjacamar/jdbc-local/1.0.28.Final/jdbc-local-1.0.28.Final-javadoc.jar-unzip/org/jboss/jca/adapters/jdbc/jdk6/WrappedPreparedStatementJDK6.html

getDeclaredmethod doesn't follow the inheritance heirarchy to find a method like getMethod does.

As the method is public , I suggest you use getMethod and you won't need to know the class which actually implements the method.

In fact you should be able to call the public method directly, but I assume there is a reason you have to use reflection.

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