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
?
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.
Wrapper Classes A wrapper class is an object that encapsulates a primitive type.
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.
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.
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
Strange but true:
this.getClass().getMethod("Test",int.class).invoke(this, 10);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With