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. Advertisements

  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. Advertisements

  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. Advertisements

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:
    568
    =?ISO-8859-1?Q?S=F8ren_Bak?=
    Aug 27, 2003
  2. munki
    Replies:
    5
    Views:
    3,462
    Michael Borgwardt
    Oct 8, 2003
  3. garfield
    Replies:
    3
    Views:
    665
    John C. Bollinger
    Oct 30, 2003
  4. Dimitri Pissarenko

    Hashcode of primitive types

    Dimitri Pissarenko, Jan 29, 2004, in forum: Java
    Replies:
    5
    Views:
    6,621
    Hylander
    Jan 29, 2004
  5. Replies:
    7
    Views:
    927
    Victor Bazarov
    May 9, 2005
  6. pek
    Replies:
    2
    Views:
    1,296
  7. Daniel Pitts
    Replies:
    7
    Views:
    726
  8. Nasser M. Abbasi
    Replies:
    74
    Views:
    5,043
Loading...