Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 413
Earth Engine Avatar asked Nov 16 '12 06:11

Earth Engine


People also ask

When a primitive data type is passed to a method as argument?

When we pass primitive types as method arguments, they're passed by value. Or rather, their value is copied and then passed to the method. When we declare and initialize int x = 0; , we've told Java to keep a 4-byte space in the stack for the int to be stored in.

How do we call an object that corresponds to value of primitive type?

Wrapper Classes A wrapper class is an object that encapsulates a primitive type.

Which method is used to get methods using reflection?

The getConstructors() method is used to get the public constructors of the class to which an object belongs. The getMethods() method is used to get the public methods of the class to which an object belongs.

How private method can be called using reflection?

If we want to access Private Field and method using Reflection we just need to call setAccessible(true) on the field or method object which you want to access. Class. getDeclaredField(String fieldName) or Class. getDeclaredFields() can be used to get private fields.


2 Answers

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

like image 158
Mukul Goel Avatar answered Sep 21 '22 11:09

Mukul Goel


Strange but true:

this.getClass().getMethod("Test",int.class).invoke(this, 10); 
like image 41
Miserable Variable Avatar answered Sep 20 '22 11:09

Miserable Variable