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

Exception or error:

I have the following two methods in a class:

public void Test(int i){
public void Test(Integer i){

The following line of code

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

prints 2 , how to make it print 1?

How to solve:

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

You could use

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


Strange but true:

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

Leave a Reply

Your email address will not be published. Required fields are marked *