How to use getMethod() with primitive types?

JavaReflection

Java Problem Overview


This is the class:

class Foo {
  public void bar(int a, Object b) {
  }
}

Now I'm trying to get "reflect" this method from the class:

Class c = Foo.class;
Class[] types = { ... }; // what should be here?
Method m = c.getMethod("bar", types);

Java Solutions


Solution 1 - Java

There's just an int.class.

Class[] types = { int.class, Object.class };

An alternative is Integer.TYPE.

Class[] types = { Integer.TYPE, Object.class };

The same applies on other primitives.

Solution 2 - Java

The parameter of the method is a primitive short not an Object Short.

Reflection will not find the method because you specified an object short. The parameters in getMethod() have to match exactly.

EDIT: The question was changed. Initially, the question was to find a method that takes a single primitive short.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionyegor256View Question on Stackoverflow
Solution 1 - JavaBalusCView Answer on Stackoverflow
Solution 2 - JavapaulturnipView Answer on Stackoverflow