1

I am trying to find the method of a PreparedStatement (ps):

Method method = ps.getClass().getMethod("setLong", int.class, Class.forName("java.lang.Long"));
method.setAccessible(true);
method.invoke(ps, fieldIndex, value);

but it isn't found. I have to use Class.forName("java.lang.Long") instead of Long.class.

For String it works:

Method method = ps.getClass().getMethod("setString", int.class, Class.forName("java.lang.String"));
method.setAccessible(true);
method.invoke(ps, fieldIndex, value);

What am I doing wrong? Any idea? Is the namespace of Long wrong?

4
  • 2
    Why on earth would you use reflection, if you already have all values in hand? Simply call ps.setLong(fieldIndex, value). Commented Mar 6, 2018 at 10:13
  • @Seelenvirtuose maybe (one can always hope) this is one of those Minimal, Complete, and Verifiable examples the legends talk about. And the setAccessible call indicates that those methods are not visible to the calling code. But they are, so maybe MrSct just thought they weren't :/ Commented Mar 6, 2018 at 10:21
  • I have a string variable that tells me which type have to use like that: Method method = ps.getClass().getMethod("set"+ methodType, int.class, Class.forName(getFullNameClass(methodType))); Commented Mar 6, 2018 at 10:45
  • That still sounds like an xy problem. The actual type is determined by the statement or target column and whatever set… method you will use, the driver will attempt to convert the argument to the target type. It would be very strange, if you can’t just use setObject(int,Object) or setObject(int,Object,type:int) Commented Mar 12, 2018 at 12:37

1 Answer 1

10

The second argument is a long, not a Long:

Method method = ps.getClass().getMethod("setLong", int.class, long.class);

Also, for a String, you don't need to call Class.forName("java.lang.String"): String.class would work as well.

But as commented, if you already have a PreparedStatement instace, you could simply call:

ps.setLong(fieldIndex, value);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.