Java reflection with primitive types

Discussion in 'Java' started by Zach, Jun 8, 2005.

  1. Zach

    Zach Guest

    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
     
    Zach, Jun 8, 2005
    #1
    1. Advertising

  2. Zach

    Bjorn Abelli Guest

    "Zach" wrote...

    > 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
     
    Bjorn Abelli, Jun 8, 2005
    #2
    1. Advertising

  3. Zach

    John Currier Guest

    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
     
    John Currier, Jun 8, 2005
    #3
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. =?ISO-8859-1?Q?S=F8ren_Bak?=

    Collections API for primitive types

    =?ISO-8859-1?Q?S=F8ren_Bak?=, Aug 27, 2003, in forum: Java
    Replies:
    0
    Views:
    409
    =?ISO-8859-1?Q?S=F8ren_Bak?=
    Aug 27, 2003
  2. Replies:
    7
    Views:
    605
    Victor Bazarov
    May 9, 2005
  3. pek
    Replies:
    2
    Views:
    1,078
  4. Daniel Pitts
    Replies:
    7
    Views:
    483
  5. Nasser M. Abbasi
    Replies:
    74
    Views:
    3,477
Loading...

Share This Page