Generically calling a method on an object

Hello,
I am trying to write a small utility method to generically call a method on an object.
This is what I have.
    public static void doCall(Object o, String methodName, Object ... args){
        Class[] types = new Class[args.length];
        int i = 0;
        for(Object arg : args){
            types[i] = arg.getClass();
        try {
            Method m = o.getClass().getMethod(methodName, types);
            m.invoke(o, args);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("Error dynamically calling method " + methodName + " on " + o.toString());
    }It doesn't work because it can't find the method. If I hard code the parameter types as "new Object[] {Double.TYPE}" it works fine (on methods that take a double).
So, my question is, how can I generically set up the parameter types based on the types of the arguments?
Thanks,
~Eric

The problem is not on calling agr.getClass(), your primitive double is already autoboxed to a Double object. It is the doCall(...) method who expects an object, not a primitive. So when giving it a primitive value, java autoboxes it to the corresponding object type.
This means your attempt will only work if the methods to call do not have any primitives as parameters.
Test this code:
public class GenericMethodCaller {
     public static void doCall(Object o, String methodName, Object ... args){
        Class[] types = new Class[args.length];
        int i = 0;
        for(Object arg : args){
            types[i++] = arg.getClass();
        try {
            Method m = o.getClass().getMethod(methodName, types);
            m.invoke(o, args);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("Error dynamically calling method " + methodName + " on " + o.toString());
     public static void main(String[] args) {
          Callable callee = new Callable();
          callee.callabelMethod(10d);          
          GenericMethodCaller.doCall( callee, "callabelMethod", 10d ); // 10d gets autoboxed to a Double object.
class Callable {
     public void callabelMethod(Double o) {
          System.out.println("callabelMethod(Double o) called");
     public void callabelMethod(double o) {
          System.out.println("callabelMethod(double o) called");
}The output will be:
callabelMethod(double o) called
callabelMethod(Double o) called
- Roy

Similar Messages

  • Calling a method in BPM Object from jsp page

    hi all,
    I try to call a method from BPM Object using <f:invokeUrl >
    I change server side method properties to yes.
    and then how can i get request and response object inside the BPM method.
    Thanks.

    Thanks for ur response,
    But i mention about BPM method inside BPM Object.
    i found this inside the documentation.
    methodName(Fuego.Net.HttpRequest request, Fuego.Net.HttpResponse response)
    i need to match above BPM method and <f:invokeUrl > tag. am i right?
    But i don't know how to create method with argument "Fuego.Net.HttpRequest request, Fuego.Net.HttpResponse response" inside BPM Object.
    I can't find any place to define method argument inside Oracle BPM studio.
    I don't know how to parse argument like "Fuego.Net.HttpRequest request, Fuego.Net.HttpResponse response"
    With Regards,
    Wai Phyo
    Edited by: user8729650 on Sep 9, 2009 7:03 PM
    Edited by: user8729650 on Sep 9, 2009 9:20 PM

  • Calling a method in BPM Object from jsf page

    Hi All,
    How do I call a method in BPM object from JSF page? Is it possible to invoke it in a manner similar to invoking a method from managed bean in JSF application?
    Please help.
    Thanks and Regards,
    Veronica

    You can use f:invoke (or f:invokea to with parameters)
    For ajax calls, you can use f:invokeUrl to get the URL to a particular method within your BPM object, although make sure the Server-Side Method property is set to Yes.
    http://download.oracle.com/docs/cd/E13154_01/bpm/docs65/taglib/index.html

  • JUNIT : how to call static methods through mock objects.

    Hi,
    I am writing unit test cases for an action class. The method which i want to test calls one static method of a helper class. Though I create mock of that helper class, but I am not able to call the static methods through the mock object as the methods are static. So the control of my test case goes to that static method and again that static method calls two or more different static methods. So by this I am testing the entire flow instead of testing the unit of code of the action class. So it can't be called as unit test ?
    Can any one suggest me that how can I call static methods through mock objects.

    The OP's problem is that the object under test calls a static method of a helper class, for which he wants to provide a mock class
    Hence, he must break the code under test to call the mock class instead of the regular helper class (because static methods are not polymorphic)
    that wouldn't have happened if this helper class had been coded to interfaces rather than static methods
    instead of :
    public class Helper() {
        public static void getSomeHelp();
    public class MockHelper() {
        public static void getSomeHelp();
    }do :
    public class ClassUnderTest {
        private Helper helper;
        public void methodUnderTest() {  // unchanged
            helper.getSomeHelp();
    public interface Helper {
        public void getSomeHelp();
    public class HelperImpl implements Helper {
        public void getSomeHelp() {
            // actual implementation
    public class MockHelper implements Helper {
        public void getSomeHelp() {
            // mock implementation
    }

  • Vector, calling a method of an object in a Vector

    hi and sorry for my poor english.
    problem:
    i have a Vector:
    Vector objects = new Vector();i put some Objects in this Vector:
    objects.addElement(new testObject());in the class testObejct() i've defined some methods like:
    public method1() {
        System.out.println("bla");
    }how can i call that methods now by my Vector?
    this doesn work :(
    objects.lastElement().method1();thanx :)

    The vector method lastElement() returns an Object type so you need to cast the Object retrieved to the correct type before you can call one of it's methods.
    Try something like
    testObject to = (testObject)objects.lastElement();
    to.method1();you can use instanceof to test if a class is a member of a particular type

  • Calling Java Method on an Object?????

    It is quite clear how to call a method that passes an argument in Express i.e.
    <invoke name='methodName' class='com.waveset.ui.ClassName'>
    <ref>argument</ref>
    </invoke>
    Essentially this is the same as calling
    methodName( argument );
    How is is possible to call a method in a class that operates on the object i.e.
    object.methodName( );
    i.e.
    com.waveset.object.GenericObject has a method called toMap( ) which returns the GenericObject back as a Map.
    A User View is a GenericObject so how do you call a method on the User object i.e.
    <ref>user</ref>.someMethod( ); or user.toMap( ); rather than
    <invoke name='toMap' class='com.waveset.object.GenericObject'>
    <ref>user</ref>
    </invoke>
    This will not work because there is no method called toMap that takes a GenericObject as a argument.
    I can't find any documentation that addresses this issue.

    The invoke tag is handled differently depending on its arguments.
    <invoke name='methodName' class='com.something'>
       <ref>someVariable</ref>
    </invoke>is calling static method methodName on class com.something and passes someVariable as an argument
    If you leave the class name out of the invoke, it calls the method on the first variable within the tag (the object). The remaining variables act as arguments to the method.
    Here's a trivial example. It creates a HashMap and then performs a 'get' on one of its keys (name)
    <invoke name='get'>
        <new class='java.util.HashMap'>
            <map>
                 <s>name</s>
                 <s>Darth Vader</s>
                 <s>type</s>
                 <s>villain</s>
            </map>
        </new>
        <s>name</s>
    </invoke>Here's a more complex example:
    <new class='com.waveset.object.Resource'>
         <invoke name='toXml'>
                <invoke name='getObject' class='com.waveset.ui.FormUtil'>
                       <ref>:display.session</ref>
                       <s>Resource</s>
                       <s>Active Directory Resource Adapter</s>
                </invoke>
         </invoke>
    </new>This calls the static getObject method returns a com.waveset.object.PersistentObject, which in turn has toXML invoked on it (returning a java.lang.String serialized version of the object) which is then used as the argument for constructing a com.waveset.object.Resource object.
    Jason

  • How to call paint() method during creating object

    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    import javax.swing.event.*;
    class SomeShape extends JPanel {
         protected static float width;
         protected BasicStroke line = new BasicStroke(width, BasicStroke.CAP_ROUND, BasicStroke.CAP_ROUND);
    class Oval extends SomeShape {
         Oval(float width) {
              this.width = width;
              line = new BasicStroke(width, BasicStroke.CAP_ROUND, BasicStroke.CAP_ROUND);
              repaint();
         public void paint(Graphics g) {
              Graphics2D pen = (Graphics2D)g;
              int i = 10;
              super.paint(g);
                   g.setColor(Color.blue);
                   g.drawOval(90, 0+i, 90, 90);
                   System.out.println("paint()");
    public class FinalVersionFactory {
        JFrame f = new JFrame();
        Container cp = f.getContentPane();
        float width = 0;
        SomeShape getShape() {
             return new Oval(width++); //I want to paint this oval when I call getShape() method
         public FinalVersionFactory() {
              f.setSize(400, 400);
    //          cp.add(new Oval()); without adding
              cp.addMouseListener(new MouseAdapter() {
                   public void mouseReleased(MouseEvent e) {
                        getShape();
              f.setVisible(true);
         public static void main(String[] args) { new FinalVersionFactory(); }
    }I need help. When I cliked on the JFrame nothing happened. I want to call paint() method and paint Oval when I create new Oval() object in getShape(). Can you correct my mistakes? I tried everything...Thank you.

    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    import javax.swing.event.*;
    class SomeShape extends JPanel {
         protected static float width;
         protected static BasicStroke line = new BasicStroke(width, BasicStroke.CAP_ROUND, BasicStroke.CAP_ROUND);
    class Oval extends SomeShape {
         static int x, y;
         Oval(float width, int x, int y) {
              this.width = width;
              this.x = x;
              this.y = y;
              line = new BasicStroke(width, BasicStroke.CAP_ROUND, BasicStroke.CAP_ROUND);
         public void paint(Graphics g) {
              Graphics2D pen = (Graphics2D)g;
                   g.setColor(Color.blue);
                   pen.setStroke(line);
                   g.drawOval(x, y, 90, 90);
                   System.out.println("Oval.paint()"+"x="+x+"y="+y);
    class Rect extends SomeShape {
         static int x, y;
         Rect(float width, int x, int y) {
              this.width = width;
              this.x = x;
              this.y = y;
              line = new BasicStroke(width, BasicStroke.CAP_ROUND, BasicStroke.CAP_ROUND);
         public void paint(Graphics g) {
              Graphics2D pen = (Graphics2D)g;
                   g.setColor(new Color(250, 20, 200, 255));      
                   pen.setStroke(line);
                   g.drawRect(x, y, 80, 80);
                   System.out.println("Rect.paint()"+"x="+x+"y="+y);
    public class FinalVersionFactory extends JFrame {
        Container cp = getContentPane();
        float width = 0;
        int x = 0;
        int y = 0;
            boolean rect = false;
        SomeShape getShape() {
             SomeShape s;
              if(rect) {
                   s = new Rect(width, x, y);
                   System.out.println("boolean="+rect);
              } else {
                   s = new Oval(width++, x, y);
                   System.out.println("boolean="+rect);
              System.out.println("!!!"+s); //print Oval or Rect OK
              return s; //return Oval or Rect OK
         public FinalVersionFactory() {
              setSize(400, 400);
              SomeShape shape = getShape();
              cp.add(shape); //First object which is add to Container(Oval or Rect), returned by getShape() method
              //will be paint all the time. Why? Whats wrong?
              cp.addMouseListener(new MouseAdapter() {
                   public void mouseReleased(MouseEvent e) {
                        x = e.getX();
                        y = e.getY();
                        rect = !rect;
                        getShape();
                        cp.repaint(); //getShape() return Oval or Rect object
                                      //but repaint() woks only for object which was added(line 67) as first
              setVisible(true);
         public static void main(String[] args) { new FinalVersionFactory(); }
    }I almost finish my program but I have last problem. I explained it in comment. Please look at it and correct my mistakes. I will be very greatful!!!
    PS: Do you thing that this program is good example of adoption Factory Pattern?

  • Calling a method of another Object

    I have 3 panels, panelMain, panelA and panelB
    panelMain is the "main" panel which holds panelA and panelB.
    When a button is clicked in panelB, I wish to call up the a method in panelA, but I get the error
    "non-static method cannot be referenced froma static context"
    What might be the problem?

    It's normal, to call a method of an instance, you must have a handler on the instance. In your case, panelB must have a handler ( a kind of reference if you want) on panelA (i.e. panelB must know the instance of panelA to call a method of panelA).
    For example :
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    class PanelB extends JPanel {
         public PanelA panelA; // to keep the instance of panelA needed to call the methods of panelA
         JLabel messageLabel;
         public PanelB() {
              super();// optional
              JLabel label = new JLabel("This is the panelB");
              add(label);
              JButton button = new JButton("Call panelA method");
              button.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent e) {
                        panelA.showMessage(); // call a method of panelA
              add(button);
              messageLabel = new JLabel("");
              add(messageLabel);
         public void setPanelA(PanelA p) { // initialize panelA with the required instance
              panelA = p;
         public void showMessage() {
              messageLabel.setText("Message from panelA");
    class PanelA extends JPanel {
         public PanelB panelB; // to keep the instance of panelB needed to call the methods of panelB
         JLabel messageLabel;
         public PanelA() {
              super();// optional
              JLabel label = new JLabel("This is the panelA");
              add(label);
              JButton button = new JButton("Call panelB method");
              button.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent e) {
                        panelB.showMessage(); // call a method of panelB
              add(button);
              messageLabel = new JLabel("");
              add(messageLabel);
         public void setPanelB(PanelB p) { // initialize panelA with the required instance
              panelB = p;
         public void showMessage() {
              messageLabel.setText("Message from panelB");
    public class MainPanel extends JPanel {
         public MainPanel() {
              super(); // optional
              setLayout(new GridLayout(1,2,0,0));
              PanelA pa = new PanelA();
              add(pa);
              PanelB pb = new PanelB();
              add(pb);
              pa.setPanelB(pb);
              pb.setPanelA(pa);
         public static void main(String[] arg) {
              JFrame f = new JFrame("My Frame");
              f.getContentPane().add(new MainPanel());
              f.setBounds(100,100,300,300);
              f.setVisible(true);
    }I hope this helps,
    Denis

  • How can I call a method of an object that is stored in an ArrayList?

    Hello,
    I am working on a simple game.
    I have my own collection class that can contain some Brick objects.
    That class looks like this:
    class MyCollection<Brick>
          ArrayList<Brick> list = new ArrayList<Brick>();
          public void add(Brick obj)
                list.add(obj);
         public int get(int i)
                return list.get(i);
         public int length()
               return list.size();
    }My Brick class is abstract and contains this method:
    public abstract int getXpos();That method is overridden by the subclass Brick_type1 (which, of course, extends Brick) and returns an int.
    In my main class I try to call the getXpos() method but I cannot call if for an unknown reason:
    MyCollection mc = new MyCollection<Brick>();
    Brick_type1 bt = new Brick_type1(10);
    mc.add(bt);
    for(int i = 0; i<mc.length(); i++)
                System.out.println(bc.get(i).getXpos());   // getXpos() does not exist, says the compilatorbc.get(i) should return a Brick that contains the getXpos() method, so why can´t I call it?

    Roxxor wrote:
    Sorry, it should be:
    public Brick get(int i)
    return list.get(i);
    }...so it actually returns a Brick, but I still cannot call the getXpos() method for some reason.Is this also just a typo?
    MyCollection mc = new MyCollection<Brick>();

  • Calling a method from an object

    Hi guys,
    I'm trying to use the "testTemperature" method to access the object type "WeatherStation" (already created in my project) and return its initial temperature value.
    I keep getting an error message when i do it. Can someone tell me where i'm going wrong?
    public class Reporter
        // instance variables
        private WeatherStation ws;
        private WeatherReport wr;
        /** Constructor for objects of class Report
        public Reporter()
            ws = new WeatherStation("Tropical");
            wr = new WeatherReport();
        /** Returns initial temperature value
        public int testTemperature()
            return WeatherStation.temperature;
         * Constructor for objects of class Report
        public Reporter(String where)
            ws = new WeatherStation(where);
            wr = new WeatherReport();
    }

    flounder wrote:
    You are trying to access temperature statically. You have created a WeatherStation object so you should accessing temperature via that object instead.Yeah, that was what i wanted to do.
    I have now sorted that out now.
    I've got a problem though.....
    When i compile, it says there is no syntax error, but when i run the method, it gives me this error message ---> http://i36.tinypic.com/14ne3wl.jpg
    Here's my code....
    public class Reporter
        // instance variables
        private WeatherStation ws;
        private WeatherReport wr;
        private WeatherStation temperature;
        /** Constructor for objects of class Report
        public Reporter()
            ws = new WeatherStation("Tropical");
            wr = new WeatherReport();
        /** Returns initial temperature value
        public int testTemperature()
            return temperature.getTemperature();
         * Constructor for objects of class Report
        public Reporter(String where)
            ws = new WeatherStation(where);
            wr = new WeatherReport();
    }Anyone got an idea where i'm going wrong?
    Edited by: LevelSix on Nov 28, 2008 10:17 AM

  • Calling a method on top object?

    Say I have my top level class, App extends JFrame, and I want to call the getlocation method on it within on of its functions. I cant do super().getLocation. So what do I do?

    Here's the code.
    public class App extends javax.swing.JFrame {
        Rectangle _captureArea;   
        public App()  {
            initComponents();
            captureButton.addActionListener(new ActionListener( ) {      
                 public void actionPerformed(ActionEvent ev) {
                    _captureArea = new Rectangle(App.this.getLocationOnScreen().getX()-320, App.this.getLocationOnScreen().getY(), 320, 45);
        } //end of constructor
    }Here is the error:
    init:
    deps-jar:
    Compiling 1 source file to C:\Documents and Settings\James Kovacs\TextTwistPlayer\build\classes
    C:\Documents and Settings\James Kovacs\TextTwistPlayer\src\App.java:39: cannot find symbol
    symbol  : constructor Rectangle(double,double,int,int)
    location: class java.awt.Rectangle
                    _captureArea = new Rectangle(App.this.getLocationOnScreen().getX()-320, App.this.getLocationOnScreen().getY(), 320, 45);
    1 error
    BUILD FAILED (total time: 1 second)Message was edited by:
    jdk2006

  • Error when calling add method of UDO object

    Hi all
    i've created a UDO object. when i invoke the method "add" i get the following error message: "Ref count for this object is higher then 0"
    anyone can tell me how to fix this?
    appreciate the help
    Yoav

    Hi YECHIEL SCHUSSEIM  ,
                                                This message will come unless u have garbage collect ur objects,
                               After u have created ur fields u have to collect ur bojects as
    '/////*********************   after  all fields are added succesfully
            ' to release the object
            System.Runtime.InteropServices.Marshal.ReleaseComObject(oUserFieldsMD)
            GC.Collect() 'Release the handle to the table
                  Now u r going to create UDO
    '///***************************************  after the udo is successfully created u have garbage collect the ob ject as
                           ' to release the object
            System.Runtime.InteropServices.Marshal.ReleaseComObject(oUserObjectMD)
            GC.Collect() 'Release the handle to the table
                         I hope it helps
    Regards
    V.Rangarajan

  • Receiving null pointer exception when calling a method of the object

    class Employee {
         private String name;
         private int age;
         private double salary;
         private String dob;
         public void setEmp(String name, int age, double salary, String dob){ //setter method
              this.name = name;
              this.age = age;
              this.salary = salary;
              this.dob = dob;
         public Employee getEmp(){ //getter method
              return this;
    public class EmployeeDemo {
         public static void main(String[] args) {
              String str1 = "John_Stone251000.0005051975";
              String str2 = "Jane Doe  242000.0006071980";
              String str3 = "Will Smith356000.5005051960";
              String[] str = {str1,str2,str3};
              Employee[] emp = new Employee[3];
              String emp_name, emp_dob;
              int emp_age;
              double emp_sal;
              for(int i=0;i<str.length;i++){
                   emp_name=str.substring(0,10);
                   emp_age=Integer.parseInt(str[i].substring(10,12));
                   emp_sal=Double.parseDouble(str[i].substring(12,19));
                   emp_dob=str[i].substring(19,26);
                   emp[i].setEmp(emp_name,emp_age,emp_sal,emp_dob); //NullPointerException error
    After compiling both classes and running:
    output error: Exception in thread "main" java.lang.NullPointerException
            at EmployeeDemo.main(EmployeeDemo.java:21)I don't understand why I am getting the NullPointerException error and how to fix it?

    I expect the following program to output the String "Victor Shakapopulis":
    public class Test
      public static void main (String[] args)
        String[] data = new String[3];
        System.out.println(data[0]);
    }Will it? Or will the program output the String "hello world". If neither of those, what will the program output?
    Have the program output data[1] and data[2] as well. What can you conclude about the contents of an array after you create it?

  • Calling Methods from Business Object BUS2032

    Hi all,
              Is it possible to call methods from the Business Object BUS2032.
       If so, how can it be done?? 
    Regards,

    Hi Marv,
    you sure can. Here is an extract from the SAP Help. I found it at http://help.sap.com/saphelp_46c/helpdata/en/c5/e4ad71453d11d189430000e829fbbd/frameset.htm
    <b>Programmed Method Call</b>
    Call (fictitious) method Print of object type VBAK (sales document). The method receives the parameters Paperformat and Printertype as input.
    * Call method Print of object type VBAK
    * Data declarations
    DATA: VBAK_REF TYPE SWC_OBJECT.
    SWC_CONTAINER CONTAINER.
    * Create object reference to sales document
    SWC_CREATE_OBJECT VBAK_REF 'VBAK' <KeySalesDoc>
    * Fill input parameters
    SWC_CREATE_CONTAINER CONTAINER.
    SWC_SET_ELEMENT CONTAINER 'Paperformat' 'A4'.
    SWC_SET_ELEMENT CONTAINER 'Printertype' 'Lineprinter'.
    * Call Print method
    SWC_CALL_METHOD VBAK_REF 'Print' CONTAINER.
    * Error handling
    IF SY-SUBRC NE 0.
    ENDIF.
    Cheers
    Graham

  • Calling Standard Method of Object

    Dear All,
         I had requirement to call standard method 'CANCEL' of Object(MOVEINDOC) in abap program.But the problem is that the method is not released.How can i call this method in abap program.

    Thanks to all.
    I found in Metalink that this is really NOT supported by Oracle Objects : http://metalink.oracle.com/metalink/plsql/ml2_documents.showDocument?p_database_id=FOR&p_id=189601.995
    Zlatko, your solution is pretty but i am not sure it is usable for my wide object hierarchy (very wide) which i have to rewrite.

Maybe you are looking for

  • What is backburnerserver? It's a hidden process... What is it doing?

    What is backburnerserver? It's a hidden process... here: /usr/discreet/backburner/backburnerServer  What is it doing?

  • Posfix error writing message: File too large

    I was looking for a reason for my Mac hanging occasionally. In Console I found the following recurring error message. 10/2/11 8:15:19 PM     postfix/master[656]     daemon started -- version 2.5.5, configuration /etc/postfix 10/2/11 8:16:00 PM     po

  • Stopping right click selecting tab in JTabbedPane

    Hello all, This may be a really simple thing + I'm probably being thick, but is there a way to prevent a right click changing the selected tab on a JTabbedPane. I tried consuming the MouseEvent, but that didn't seem to work. Couldn't find an answer a

  • Downloading LR 5 Upgrade But stops

    I just bought a Lightroom 5 upgrade.  When I download the product, it freezes, then gives the error message "Unknown Network Error."  I already checked my internet settings, connection, and speed, and everything seems to be in order.  Can you help me

  • IFS Schema password error

    After setting my ifs schema password with ifsconfig and try to run ifssetup, this is what I get: Enter password for ifs schema names IFSSYS:<password> ERROR ORA-01034: Oracle not available (but DB is running) Invalid password specified or Oracle 8i d