| Author |
Accessing methods with primitive argument via reflection
|
kumarjit banerjee
Ranch Hand
Joined: Mar 27, 2011
Posts: 32
|
|
Can a method be invoked via reflection api of java which contains a primitive in the argument.
For example I want to access the method "show" from another class via reflection.
public class Example1{
public void show(int i,String s){
System.out.println("Value is "+i+" "+s);
}
}
|
 |
Matthew Brown
Bartender
Joined: Apr 06, 2010
Posts: 3795
|
|
Yes, it can. Which part are you having trouble with? Getting the Method object or calling invoke on it?
If it's the first part - note that you can get Class objects representing primitives from the appropriate wrapper class. For example, Integer.TYPE is "The Class instance representing the primitive type int" according to the Javadocs.
For the second part, the Javadocs for invoke say: "Individual parameters are automatically unwrapped to match primitive formal parameters".
So something like this should work:
|
 |
kumarjit banerjee
Ranch Hand
Joined: Mar 27, 2011
Posts: 32
|
|
Matthew Brown wrote:Yes, it can. Which part are you having trouble with? Getting the Method object or calling invoke on it?
If it's the first part - note that you can get Class objects representing primitives from the appropriate wrapper class. For example, Integer.TYPE is "The Class instance representing the primitive type int" according to the Javadocs.
For the second part, the Javadocs for invoke say: "Individual parameters are automatically unwrapped to match primitive formal parameters".
So something like this should work:
Thanks very much. It worked.
|
 |
Darryl Burke
Bartender
Joined: May 03, 2008
Posts: 4167
|
|
you can get Class objects representing primitives from the appropriate wrapper class. For example, Integer.TYPE ...
Isn't Integer.TYPE the same as int.class?
|
luck, db
There are no new questions, but there may be new answers.
|
 |
Matthew Brown
Bartender
Joined: Apr 06, 2010
Posts: 3795
|
|
If such a thing exists, almost certainly .
|
 |
Campbell Ritchie
Sheriff
Joined: Oct 13, 2005
Posts: 32712
|
|
Matthew Brown wrote:If such a thing exists, almost certainly  .
Can't be. Try this
java IntClassDemo
intClass == Integer.TYPE? true
|
 |
Matthew Brown
Bartender
Joined: Apr 06, 2010
Posts: 3795
|
|
Campbell Ritchie wrote:
Matthew Brown wrote:If such a thing exists, almost certainly  .
Can't be. Try this
Hang on. It's late on a Friday night, and I really shouldn't be trying to follow code at this point...but doesn't that prove that they are the same, which is what I just said?
|
 |
Campbell Ritchie
Sheriff
Joined: Oct 13, 2005
Posts: 32712
|
|
Matthew Brown wrote:. . . but doesn't that prove that they are the same, which is what I just said?
Damn! He noticed!
Yes, of course they are the same.
|
 |
 |
|
|
subject: Accessing methods with primitive argument via reflection
|
|
|