Java reflection with primitive types

Z

Zach

I want to call a class function through invoke(...) in class Method. If
this function's arguments are different primitive types, can I call it
with invoke(...)? For example, how can I call foo() in class A in
following example?

public class A
{
public A() {}

public int foo(int a, boolean b)
{
...
}
}

Is it doable?

Thanks a lot!
Zach
 
B

Bjorn Abelli

...
I want to call a class function through invoke(...) in class
Method. If this function's arguments are different primitive
types, can I call it with invoke(...)? For example, how can
I call foo() in class A in following example?

public class A
{
public A() {}

public int foo(int a, boolean b)
{
...
}
}

Is it doable?

Yes, it is.

Just use the corresponding wrapper for primitive types.

int --> Integer
boolean --> Boolean
etc..

// Bjorn A
 
J

John Currier

Class[] paramTypes = new Class[] {int.class, boolean.class};
Method foo = A.class.getMethod("foo", paramTypes);
Object[] params = new Object[] {new Integer(55), Boolean.TRUE};
int rc = ((Integer)foo.invoke(new A(), params)).intValue();
System.out.println("foo returned " + rc);

John
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,578
Members
45,052
Latest member
LucyCarper

Latest Threads

Top