Reputation: 621
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)
Update: I forgot to say that we are using Java 1.5 (Yeah! I know).
Upvotes: 1
Views: 370
Reputation: 533492
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.
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.
Upvotes: 1
Reputation: 298143
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)
.
Upvotes: 1