Passing functions( methods ) as arguements.

I am new to java and I need to pass a method to another method within the same class. In C++ you could create a pointer to a function and pass that pointer. Can I do something like that in Java and if so How? Thanks in advance.
Barkley

I am new to java and I need to pass a method to
another method within the same class. In C++ you
could create a pointer to a function and pass that
pointer. Can I do something like that in Java andif
so How? Thanks in advance.
BarkleyActually there is no reason for this. You dont have
to pass the method to call it, especially since they
are in the same class
class X
void Method1()
void Method2()
Method1();
//or
this.Method1();
I think the original poster wants to be able to either: a) specify a method to call at run-time, not at compile-time OR b) specify a function that some other piece of code (that the coder has no control over) will execute upon a given event. These are the typical uses for function pointers are used for in my experience. This allows things like API call-back functions, etc in Windows programming.
As many people have suggested, the same thing can be done in Java using interfaces (as were all the "listener" classes in the Java API). A general form of this "call-back" interface would be:
public interface CallBack
  public Object func(Object o);
The Object argument and return-type above are similar to how void pointers are used in C++ allowing user data to be passed in to and out of the function thereby letting the function implementation interpret the incoming user data and letting the caller interpret the data coming out.
Now to "pass" a pointer to a function you would pass the implementer of the CallBack interface. The only difference is tacking on the ".func(...)" when
you do the actual call-back.
public class MyCallBack implements CallBack
  public Object func(Object o)
    // put implementation here...
    return null; // return something useful here maybe?
}Now do this:
MyCallBack cb = new MyCallBack();
- pass cb anywhere...the callback function would be done like this:
cb.func(...);

Similar Messages

  • Can I pass function name as a parameter to constructor?

    Hi!
    I want to create a class that extends JButton and executes some function, when released. The function for each button is different. I mean, can I write, for example:
    public class MyButton extends JButton
    public MyButton(...functionName...)
    addMouseListener(new MouseAdapter()
         public void mouseReleased(MouseEvent e)
         ...execute functionName...;
    MyButton testButton = new MyButton(printTest);
    void printTest()
    System.out.println("The button executes OK");
    (This code will not work, of cause).
    If you understood me, please answer if there is any way to pass function as a parameter ?
    Thank you in advance.

    Using reflection would work, but there is a more straightforward way. Here's what I do when I want to pass a method to be called by another object: First I declare an interface named Callback:public interface Callback
      public void run();
    }Then your class would look like this:public class MyButton extends JButton {
      private Callback doit;
      public MyButton(Callback whatToDo) {
        doit = whatToDo;
        addMouseListener(new MouseAdapter() {
          public void mouseReleased(MouseEvent e) {
            whatToDo.run();
    }and the code that creates a MyButton might look like this:Callback callMe = new Callback() {
      public void run() {
        System.exit(0);
    MyButton closeButton = new MyButton(callMe);
    closeButton.setText("Close");If you like, you can adapt this pattern to use variations of Callback that have parameters or return values.

  • Pass a method as an object to DocumentListener

    So far, I have been assigning document listeners to JTextfields within the same class as the JTextField, as in...
                   private createJTextField(){
                       JTextField t = new JTextField();
                       t.getDocument().addDocumentListener(documentListener());
                   private DocumentListener documentListener() {
                  DocumentListener listener = new DocumentListener(){
                      public void changedUpdate(DocumentEvent e){textFieldActions();}
                  public void removeUpdate(DocumentEvent e){textFieldActions();}
                         public void insertUpdate(DocumentEvent e){textFieldActions();};};
                 return listener;
                private void textFieldActions() {
                  //Do something, like search the text in the JTextField for a string;
                  }This does work, but it means I have to include similar blocks of code for every JTextField I create.
    ...so, I thought it would be better to set up a utility that I could pass the JTextField and method to, which would assign the method to the DocumentListener. Something like...
         private JTextField t;
         private Boolean b;
         private JTextFieldDocumentListenerUtility l;
         protected void setUp(){
              t = new JTextField();
              b = false;
              l = new JTextFieldDocumentListenerUtility();
         public void testDocumentListener(){
              assertFalse(b);
              l.assignAction(t, someAction());
              t.setText("bogus");
              assertTrue(b);
         private void someAction() {
              b = true;
                   }The JTextFieldDocumentListenerUtility class includes the "private DocumentListener documentListener()" method in the first block of code.
    However, I can't pass the method "as is". I think (and I need some guidance here) its because the method "someAction()" returns a void, whereas I need to pass an object to the JTextFieldDocumentListenerUtility.
    What is the tidiest way to do this, given that I'm trying to cut down duplicate code every time I create a JTextField?
    Can someone please walk me through this?

    You could use the Strategy pattern.
    Basically creating a DocumentListener implementation that accepts as parameters the JTextField and a separate "Operation" instance. Where operation would be an
    interface that would define a single operation() method (or 3 different operation methods if you want different operations performed for the changed/remove/insert events).
    Some non-tested sample code.
    public class MyListener implements DocumentListener {
        private JTextField field;
        private Operation operation;
        public MyListener(JTextField field, Operation operation) {
            this.field = field;
            this.operation = operation;
        public void changedUpdate(DocumentEvent e) { operation.changed(field); }
        public void removeUpdate(DocumentEvent e) { operation.remove(field); }
        public void insertUpdate(DocumentEvent e) { operation.insert(field); }
    }This way if you have 10 textfields that need to behave in a similar way, you'd need only create 1 Operation implementation that handles the functionality and just use
    t.getDocument().addDocumentListener(new MyListener(t, new MyStandardOperation()));Since you can't pass around only methods, you need to have a class to contain them in.
    But if you need to have several textfields that have similar functionality, you'll have the functionality contained in a single place and cut down on the boilerplate code.

  • LR 5 functions, methods, and properties not in LR 4 docs

    While we're waiting for the SDK docs, I scanned for functions, methods, and properties not documented in the LR 4 SDK.  Here's what I found:
    LrCatalog
    Methods:
    assertHasReadAccess
    buildSmartPreviews (array of LrPhoto)
    createPublishService
    createVirtualCopies
    getPhotoByLocalId
    withReadAccessDo
    Properties:
    allPhotos
    hasCatalogAccess
    hasReadAccess
    hasWriteAccess
    path
    targetPhoto
    targetPhotos
    LrCollection
    Methods:
    getSearchDescription
    LrController
    nextPhoto
    previousPhoto
    showBezel
    showGrid
    showLoupe
    startSlideshow
    stopSlideshow
    triggerCapture
    LrDialogs
    closeFloatingDialogsForPlugin
    presentFloatingDialog
    presentWebViewDialog
    showBezel (string message, [number fadeDelay])
    showStringsDialog
    LrDigest
    HMAC
    MD4
    MD5
    SHA1
    SHA256
    SHA384
    SHA512
    LrLogger
    Methods:
    configure
    restoreConfiguration
    saveConfiguration
    wrapMethodWithTrace
    wrapMethodsWithTrace
    Properties:
    _actions
    _name
    _savedConfigurations
    will_debug
    will_error
    will_info
    will_trace
    will_warn
    LrPhoto
    Methods:
    applyDevelopSnapshot
    buildSmartPreview
    deleteDevelopSnapshot
    deleteSmartPreview
    getDevelopSnapshots
    locationIsPrivate
    readMetadata
    requestJpegThumbnail
    saveMetadata
    withSettingsForPluginDo
    Properties:
    countStackInFolderMembers
    countVirtualCopies
    isInStackInFolder
    isVirtualCopy
    localIdentifier
    masterPhoto
    path
    stackInFolderIsCollapsed
    stackInFolderMembers
    stackPositionInFolder
    uuid
    virtualCopies
    LrPhotoPictureView
    makePhotoPictureView
    LrPlugin
    nativeFunction
    LrPublishService
    delete
    getAllRemoteIds
    promptEditDialog
    LrPublishedCollection
    Methods:
    getSearchDescription
    publishSelected
    setSearchDescription
    LrPublishedCollectionSet
    Methods:
    delete
    LrPublishedPhoto
    Methods:
    getDevelopSettingsDigest
    getMetadataDigest
    LrTableUtils
    debugDumpTable
    LrUUID
    generateUUID
    LrView
    Methods:
    path_control
    square_button
    LrXml
    xmlElementToSimpleTable
    I didn't examine the classes LrExportContext, LrExportRendition, LrExportSession, LrExportSettings, LrFilterContext, LrVideoExportPreset, LrWebViewFactory.

    jarnoh wrote:
    catalog:createVirtualCopies()
    I can't get this to create multiple virtual copies .
    jarnoh wrote:
    it seems to create virtual copies for active selection.
    I assume you mean one virtual copy for each selected photo(?)
    Active selection meaning the (one) "most" selected photo, i.e. catalog:getTargetPhoto().
    jarnoh wrote:
    Takes as many copy name strings as many photos are selected.
    I tried passing array of copy name strings, and get internal error: "WFSqliteStatement:bind() - illegal data type used as value".
    I tried passing one string, which works, but then it only makes one copy.
    I tried unpacking the names array (i.e. passing each as a separat parameter) - again, it only makes one copy, it having the first name passed.
    What am I doing wrong??
    UPDATE:
    ~~~~~~~
    I'm still working on this, but note: return array is not necessarily freshly created virtual copies, nor are all photos returned guaranteed to be virtual - worth checking what gets returned at least until you've got it figured out (I don't, yet).
    I've been able to get it to create one copy, just fine, but can't get it to create multiple copies.
    Note: omitting all parameters, it creates one copy named "Copy N", or you can pass a string to be used as copy name. I just don't know how to pass multiple names and get it to create multiple copies.
    Has anybody actually gotten catalog:createVirtualCopies to create more than one virtual copy (with a single call I mean) ???
    PS - Worth noting: this function does not need to be called with catalog write access, strangely enough (but maybe that's part of the problem I'm having? - only does one copy if no catalog write access???).
    ~~~~~~~
    Thanks in advance,
    Rob

  • Using the functional methods with workflows

    Hi All,
    I'm passing the plant number to a workflow by triggering an event in a user-exit. The workflow uses a functional method of an ABAP class and retrives the plant details. While binding the functional method back to the workflow, the binding includes a partial expression like this..
    &_WI_OBJECT_ID.PLANT(W_PLANT=)&
    Here, if I give &_WI_OBJECT_ID.PLANT(W_PLANT='1000')& I get no error and the details of plant 1000 are retrived successfully. How do I pass this value dynamically?
    Regards
    Indu.

    Aditya,
    Thanks for your input. But there were no start conditions.
    The import parameter should be filled in the partial expression as &PLANT& which was not taking its value earlier. But now, its working. Thanks anyway.
    Regards
    Indu.

  • Passing a method call to a facelet tag

    Hello,
    I am trying to create a JSF confirmation box that replaces the Javascript confirm() function. I am using Seam and Rich Faces 3.2.1. The confirm box is a facelet tag that pops up a modal box with 'cancel' and a 'continue' buttons. Everything is working correctly except for one crucial piece; passing the method call for continue button.
    Here is the set up for the facelets tag in the main xhtml page:
    <at:confirm
        id="confirm"
        title="Confirm"
        message="Do you want to continue"
        buttonText="Continue"
        backingBean="#{confirmAction}"
        method="testMethodTwo"
    />Here is the code for the button inside the facelets tag:
    <a4j:commandLink
        styleClass="rdSplGr1"
        href="#"
        action="#{backingBean[method]}">
        <s:span>#{buttonText}</s:span>
    </a4j:commandLink>The method simply does nothing when the use clicks the button. I am assuming this is due to the lack of "()" however there does not seem to be a way to get those in there. I have tried the following:
    1) placing the parens like this - method="testMethodTwo()"
    2) placing the parens like this - action="#{backingBean[method]()}"
    The first does nothing, the second causes an EL exception.
    I know that it has nothing to do with the modal as I have also placed a button like this into the modal:
    <a4j:commandLink
        styleClass="rdSplGr1"
        href="#"
        action="#{confirmAction.testMethodOne()}">
         <s:span>MethodOne</s:span>
    </a4j:commandLink>That button as you can see has what I am trying to create dynamically and it works like a charm.
    So how do I pass a method call correctly? Or if that is impossible how do I solve the problem of having a the continue button having a different method assigned to it?
    Thanks for any insight into this.
    Edited by: Rhythmicdevil on Aug 4, 2008 7:57 AM

    I agree, reflection should be a last resort. An
    interface would not be useful if you don't know what
    method you want to invoke at compile time. Interfaces
    are useful when you know the method you want to
    invoke, but not the class.That's not true. This is a really lame-ass example but it shows the point.
    public interface RuntimeMethod
       public void method();
    class AClass {
       public static void main(Sting[] args)
          new AClass.handleAtRuntime(
             Factory.getRuntimeMethod(Integer.parse(args[0])));
       public void handleAtRuntime(RuntimeMethod runtime)
          runtime.method();
    class Factory
       public static getRuntimeMethod(int method)
          switch(method)
             case 0: return new RuntimeMethod
                public void method()
                   methodA();
             case 2: return new RuntimeMethod
                public void method()
                   methodB();
             default:
                throw new IllegalArgumentException("bad input");
    }

  • New Blog on ABAP OO Functional Methods

    As a special Christmas treat I've just released the latest blog on ABAP OO for Workflow - this one on using functional methods:
    /people/jocelyn.dart/blog/2006/12/19/using-functional-methods-in-workflows-and-tasks
    Enjoy!
    Regards,
    Jocelyn

    Hi Jocelyn,
    first of all, thanks for some excellent blogs on ABAP OO Workflow. Do you have any plans for writing about exception handling in ABAP OO Workflow. I think it would be very appreciated by the community to get some general guidelines on how to handle ABAP OO exceptions in workflows.
    What do you think?
    //Elvez

  • Does ExtendScript have a concept of "main" function/method like when script is included as a library

    I was just wondering whether ExtendScript has any concept like a main method, whereby if the current script is included by another script like a library import it will not execute this main function/method and only execute it when the script is run directly.
    Similar to Java's main() method and Python's __main__.
    If not, is there a workaround to mimic such behavior generically?

    I cannot reproduce this.  Can you create a very simple repro of this issue and post to OneDrive?
    Jeff Sanders (MSFT)
    @jsandersrocks - Windows Store Developer Solutions
    @WSDevSol
    Getting Started With Windows Azure Mobile Services development?
    Click here
    Getting Started With Windows Phone or Store app development?
    Click here
    My Team Blog: Windows Store & Phone Developer Solutions
    My Blog: Http Client Protocol Issues (and other fun stuff I support)

  • How can i pass rowiterator method

    hi how can i pass rowiterator method
    i got below method how can i pass it to my postchanges mothod e.g
    SmsPropertiesImpl property = getSmsProperties();
    am in jdeveloper 11.1.2.1.0
    public class SmsPartyAddressImpl extends EntityImpl {
        public RowIterator getSmsProperties() {
            return (RowIterator)getAttributeInternal(SMSPROPERTIES);
        public void postChanges(TransactionEvent e) {
            /* If current entity is new or modified */
            if (getPostState() == STATUS_NEW ||
            getPostState() == STATUS_MODIFIED) {
            /* Get the associated property for the postaladdress */
           // SmsPropertiesImpl property = getSmsProperties();
            //SmsPropertiesImpl property  = getSmsProperties();
                SmsPropertiesImpl property = new SmsPropertiesImpl();
               // SmsPartyAddressImpl property = new SmsPartyAddressImpl();
            /* If there is an associated property */
            if (property != null) {
            /* And if its post-status is NEW */
            if (property.getPostState() == STATUS_NEW) {
            * Post the property first, before posting this
            * entity by calling super below
            property.postChanges(e);
            super.postChanges(e);
    }

    hi how can i pass rowiterator method
    i got below method how can i pass it to my postchanges mothod e.g
    SmsPropertiesImpl property = getSmsProperties();
    am in jdeveloper 11.1.2.1.0
    public class SmsPartyAddressImpl extends EntityImpl {
        public RowIterator getSmsProperties() {
            return (RowIterator)getAttributeInternal(SMSPROPERTIES);
        public void postChanges(TransactionEvent e) {
            /* If current entity is new or modified */
            if (getPostState() == STATUS_NEW ||
            getPostState() == STATUS_MODIFIED) {
            /* Get the associated property for the postaladdress */
           // SmsPropertiesImpl property = getSmsProperties();
            //SmsPropertiesImpl property  = getSmsProperties();
                SmsPropertiesImpl property = new SmsPropertiesImpl();
               // SmsPartyAddressImpl property = new SmsPartyAddressImpl();
            /* If there is an associated property */
            if (property != null) {
            /* And if its post-status is NEW */
            if (property.getPostState() == STATUS_NEW) {
            * Post the property first, before posting this
            * entity by calling super below
            property.postChanges(e);
            super.postChanges(e);
    }

  • Passing a method to a method

    Hi all, is it possible for me to pass a method to a method? Or to somehow store a method as a variable or an object or in something? I'm sorry if I sound vague, I am kind of confusing myself with this question. I basically want a method to take a method to use in its method, but the method could be one of three methods.

    I agree, reflection should be a last resort. An
    interface would not be useful if you don't know what
    method you want to invoke at compile time. Interfaces
    are useful when you know the method you want to
    invoke, but not the class.That's not true. This is a really lame-ass example but it shows the point.
    public interface RuntimeMethod
       public void method();
    class AClass {
       public static void main(Sting[] args)
          new AClass.handleAtRuntime(
             Factory.getRuntimeMethod(Integer.parse(args[0])));
       public void handleAtRuntime(RuntimeMethod runtime)
          runtime.method();
    class Factory
       public static getRuntimeMethod(int method)
          switch(method)
             case 0: return new RuntimeMethod
                public void method()
                   methodA();
             case 2: return new RuntimeMethod
                public void method()
                   methodB();
             default:
                throw new IllegalArgumentException("bad input");
    }

  • Passing function parameters in a non-sequential fashon

    Consider the function below:
    function personal(Name:String,age:int,city:String):void
       trace(Name+" is "+age+ " years old and lives in "+city+ ".")
    The parameters can only(???) be passed in the order they are declared in the function as shown below.
    personal("John",40,"London"0)
    If the order is changed as: personal("London",John", 40), there will obviously be a type related error (position 2 parameter is an integer).
    Is there a way of passing function parameters as: personal(city="London",Name=John",age= 40)?
    That way one does not have to worry about the 'order' in which the parameters are passed.

    Micheal, I love such ELEGENCE.
    One more question, before I 'attempt' to go to bed!
    Below is code extracted from my main class definition.
    Notice how I 'populate' the artist object  before I pass it on as a parameter to my saveRecord function.
    It is rather clamsy, I think. Is there a better way of doing it?
    import ARTISTS
    var artist:ARTISTS = new ARTISTS;
    artist.ARTISTID = 123678;
    artist.FIRSTNAME = "Gordon";
    artist.LASTNAME = "Brown";
    artist.ADDRESS= "13 Darwin Street";
    artist.CITY= "London"
    saveRecord(artist);
    saveRecord(params:ARTISTS){
         //Some code here

  • How to pass Function code to Submit or Call transaction command

    Hi
    I have to call a report in an other report, But the problem is when i call the report through submit command i need to skip the initial screen and display an other screen. the other screen is not next screen. It  display after clicking a button on main screen.
    Is there any way to pass Function code to submit command. submit command code is as under
    SUBMIT ZADR0056
                  WITH P_AUFNR = '7000052' AND RETURN...
    Regards
    Ammad

    Hi,
       It is not possible to pass function code with submit. alternatively you can work with CALL TRANSACTION with BDCDATA.
    Or as a work arround way you can modify your code i.e check for function code or an dummy parameter which can be passed by SUBMIT statement.
    Check below code..
    Report ztest1.
    submit ZTEST2 WITH P2 = 'X' AND RETURN.
    Report ztest2
    SELECTION-SCREEN:
        PUSHBUTTON 2(10)  but1 USER-COMMAND cli1.
    PARAMETERS P2 TYPE C NO-DISPLAY. " no need to display
    AT SELECTION-SCREEN.
    IF SY-UCOMM = 'CLI1' OR P2 IS NOT INITIAL.
    message 'Button clicked' type 'S'.
    ENDIF.
    Regards,
    Ravi.

  • Passing a Method into a Constructor!!!

    Hi:
    I am new to Java Programming. Can some one explain me how to pass a Method into a Constructor? Any help is appreciated.
    Thank you in advance.

    If you are new to Java I suggest you learn more about Java before asking questions like that. It is possible to do that, but you probably didn't mean what you said.

  • Passing a method as parameter

    Hi!!
    How can I pass a method as parameter to other method? Is there any class that represents a methos like, for example, HelloWorld?
    Thanks everybody!!

    JosAH wrote:
    sweee wrote:
    How can I pass a method as parameter to other method? Is there any class that represents a methos like, for example, HelloWorld?Reflection can (sort of) do this; have a look at the API for the Method class but I prefer to define a couple of interfaces and stay far away from reflection.
    kind regards,
    Jos.. and the possibility to pass methods as arguments might also become true if we get closures in Java 7.

  • Question about functions methods and variables

    Sorry but i couldn't figure out a better title.
    When does a method alter the variables it gets directly and when does a method just alter a clone of the variables it gets?
    How about a funcion?
    for example:
    public void (int i)
    i = 4;
    sometimes this method alters the integer which was given to it directly and sometimes it automatically creates a clone of the integer and alters that one. I just can't figure out why a method would do the first or the second.
    Im trying to achieve the direct changeing of the given variable without creating an unessecary clone.
    Thank You

    Comp-Freak wrote:
    Sorry but i couldn't figure out a better title.
    When does a method alter the variables it gets directly and when does a method just alter a clone of the variables it gets?
    How about a funcion?
    for example:
    public void (int i)
    i = 4;
    sometimes this method alters the integer which was given to it directly and sometimes it automatically creates a clone of the integer and alters that one. I just can't figure out why a method would do the first or the second.
    Im trying to achieve the direct changeing of the given variable without creating an unessecary clone.
    Thank YouThats quite all right about the title, trust me we get much worse titles on this forum. Most of the time to the effect of "Plz urgentlly!!!!111one"
    In Java, all variables passed into methods are passed by value, which means that if I pass an int variable to a method, that methods argument will always be a seperate variable. There is no way to pass variables by reference so that you are altering the original variable you passed in.
    It actually works the same way for reference variables that point to a particular object.
    public Object o = new Object();
    methodOne(o);
    public void methodOne(Object oArg) {
      o == oArg;  //true
    }It is essentially the same in this case, there are two seperate reference variables here, o and oArg is created once the method is called. There is only one Object created however and both reference variables point to it, so an == check will verify this that it is true.

Maybe you are looking for