How to use getMethod() with primitive types?

17,528

Solution 1

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

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.

Share:
17,528
yegor256
Author by

yegor256

Lab director at Huawei, co-founder at Zerocracy, blogger at yegor256.com, author of Elegant Objects book; architect of Zold.

Updated on June 16, 2022

Comments

  • yegor256
    yegor256 almost 2 years

    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);
    
  • Racky
    Racky over 7 years
    And how do you invoke the method? If I want to pass boolean to such a method it does not work: invoke(null, new Object[] {myString, myBool}); ... boolean cannot be converted to Object.
  • xehpuk
    xehpuk about 7 years
    @Racky Works for me, at least syntactically. Are you using a Java version below 5 (missing Autoboxing)?