70

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);

2 Answers 2

102

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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.
@Racky Works for me, at least syntactically. Are you using a Java version below 5 (missing Autoboxing)?
3

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.

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.