Bhadresh Shiroya
Bhadresh Shiroya

Reputation: 261

Differenziate between int and Integer parameter when using reflection to call a method

public void getData(int i){
    System.out.println("1");
}
public void getData(Integer i){
    System.out.println("2");
}

The following line of code

this.getClass().getMethod("getData",Integer.class).invoke(this, 10);

prints 2 , how to make it print 1?

Upvotes: 0

Views: 57

Answers (1)

Axel
Axel

Reputation: 14159

You are requesting the method that accepts an Integer. Change that to the one that takes an int and you are done:

this.getClass().getMethod("getData",int.class).invoke(this, 10);

Note that there as int.class although int is a primitive type. It exists exactly for this reason.

Upvotes: 5

Related Questions