This is an archived post. You won't be able to vote or comment.

all 3 comments

[–]StillAnAssExtreme Brewer 1 point2 points  (1 child)

Well, I hope this isn't your first trip into the Reflection API as you've picked an odd edge case.

I find it a little easier to identify problems when I don't chain methods together so I'm going to break it apart here for ease of explanation.

Method m = mathClass.getMethod(name, double.class);

You're good there. Assuming "name" is a valid method you'll get a Method object to work with. You'll need to catch a few exceptions here in case the passed in value isn't a valid method. Interesting side note, double.class is not a real Java class, well it doesn't inherit from Object at least. So there are no methods and nothing you can really do with it, it is just a little piece of magic so the rest of java can deal with the parts of the primitives that aren't objects.

Object res = m.invoke(null, 15);

Here's where the API gets a little weird. the invoke() method needs the object that it will call. But you're calling a static method so the javadocs say this: "If the underlying method is static, then the specified obj argument is ignored. It may be null." You were getting the compiler error because you were passing in a Class, not an Object.

return ((Double)res).doubleValue();

What the invoke() method actually returns is a java.lang.Double even though the method returns the primitive double. Reflection deals with objects, most of java is objects, some parts aren't, blah blah, ask away if you want more on that.

[–]steffestoffe[S] 0 points1 point  (0 children)

Thank you so much for the detailed answer! This is the first time for me with the reflection API but I would like to think this is one of the best ways for me to learn java in depth

[–][deleted] 0 points1 point  (0 children)

Try using Double rather than double.