0

I'm trying to reflectively invoke the setXxx method of com.mysql.jdbc.PreparedStatement using the following code.

String type = getJavaTypeFromMySqlType(); // this is "String"
Class clazz = type.getClass(); // This is java.lang.String
Method method = com.mysql.jdbc.PreparedStatement.class.getDeclaredMethod("set"+type, int.class, clazz);
method.invoke(cnt, clazz.cast(pair.getValue())); 

The last line throws

java reflection object is not an instance of declaring class

What am I missing here?

cksrc
  • 2,062
  • 3
  • 24
  • 39
  • Possible duplicate of [this](http://stackoverflow.com/questions/13336057/java-reflection-object-is-not-an-instance-of-declaring-class) – Rao Jan 28 '16 at 08:04
  • Possible duplicate of [What is reflection and why is it useful?](http://stackoverflow.com/questions/37628/what-is-reflection-and-why-is-it-useful) – Andremoniy Jan 28 '16 at 08:04
  • Thank you for down voting just give the explanation though. I do know what reflection is and how to use it, the purpose here is that I'm building a framework to abstract the db interaction. Also @Rao what am I doing differently from the link you have provided? – cksrc Jan 28 '16 at 08:13

2 Answers2

1

You need to pass a com.mysql.jdbc.PreparedStatement as first parameter to Method.invoke:

method.invoke(pstmt, cnt, clazz.cast(pair.getValue())); 

The first parameter is the object on which the method is invoked (or null for static methods), the following parameters are the params passed to invoked method.
(Unfortunately the error message of Method.invoke does not mention the rejected type, in your case Integer).

wero
  • 32,544
  • 3
  • 59
  • 84
1

Instead of invoking it reflectively, you can use PreparedStatement.setObject(int, Object) or one of its siblings. If the driver supports the object conversion, then this will work transparently; but be prepared to handle SQLException if the type or the conversion to the database type is not supported.

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197