Java how to call method by reflection with primitive types as arguments

JavaReflection

Java Problem Overview


I have the following two methods in a class:

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

The following line of code

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

prints 2 , how to make it print 1?

Java Solutions


Solution 1 - Java

To call a method with primitive types as parameters using reflection :

You could use int.class

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

or Integer.TYPE

this.getClass().getMethod("Test",Integer.TYPE).invoke(this, 10);

same applies for other primitive types

Solution 2 - Java

Strange but true:

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

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
QuestionEarth EngineView Question on Stackoverflow
Solution 1 - JavaMukul GoelView Answer on Stackoverflow
Solution 2 - JavaMiserable VariableView Answer on Stackoverflow