Calling a method from an argument

I apologize if this is a duplicate question, I want to be able to call a method defined in the constructors argument list with a different method.

What follows is some code that won't compile, but this is actually the only way to describe my question. I also hope my explanation makes sense.

Main.java

....
Class0 instance = new Class0(arg0, arg1, arg2, new Class1(){
        //do something
        //do something else
        //do more stuff
    }
)
library.go(instance);
....

      

The point I want to get is that a new instance of class0 is initialized with an anonymous function. The instance is then passed to the library instance.

Class0.java

....
public Class1 action = null;
public Class0(int arg0, int arg1, int arg2, Class1 class) {
     setArg0(arg0);
     setArg1(arg1);
     setArg2(arg2);
     setAction(class);
}
public setAction(Class1 class) {
     action = class;
}
public action() {
     class;
}
....

      

Class0 is built from a constructor method and sets a function on the action field, it remains unclaimed but persists later. action () calls the function passed to the constructor.

Library.java

....
public void go(Class0 class0) {
    class0.action();
}
....

      

For the most part, Library.java is out of control, it's a channel for a third party library. go invokes a stored function of an instance object, which is basically declared through its action.

Does something like this even remotely exist in java? Is there any other way to achieve the same?

-2


source to share


2 answers


Edit: this assumes java 7.0 or earlier. It works in java 8, but lambda expressions are the most preferred.

It seems that you want to implement a callback interface.

  • create an interface using the method.
  • use the interface as a parameter to the method (constructor in your case).
  • an interface is just a reference to some object, so call the method.

Here's some code:

Kapow.java



public interface Kapow
{
    void callbackMethod();
}

      

KapowImpl.java

public class KapowImpl implements Kapow
{
    @Override
    public void callbackMethod()
    {
        System.out.println("Kapow!");
    }
}

      

Main.java

public final class Main
{
    private static void callIt(final Kapow theCallback)
    {
        theCallback.callbackMethod();
    }

    public static void main(String[] args)
    {
        Kapow kapowObject = new KapowImpl();

        callIt(kapowObject);
    }
}

      

+1


source


A good example of a "method type declaration" is java.awt.event.ActionListener

(see below). In Java 8 or higher, you can use lambda expressions for ease of use, but the principle is still the same - an interface with one method declaration for a boolean method.

/*
 * Copyright (c) 1996, 2006, Oracle and/or its affiliates. All rights reserved.
 * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 */

package java.awt.event;

import java.util.EventListener;

/**
 * The listener interface for receiving action events.
 * The class that is interested in processing an action event
 * implements this interface, and the object created with that
 * class is registered with a component, using the component's
 * <code>addActionListener</code> method. When the action event
 * occurs, that object <code>actionPerformed</code> method is
 * invoked.
 *
 * @see ActionEvent
 * @see <a href="http://java.sun.com/docs/books/tutorial/post1.0/ui/eventmodel.html">Tutorial: Java 1.1 Event Model</a>
 *
 * @author Carl Quinn
 * @since 1.1
 */
public interface ActionListener extends EventListener {

    /**
     * Invoked when an action occurs.
     */
    public void actionPerformed(ActionEvent e);

}

      

Here's a quick example of how to use this pattern:

public static void main(String[] args) {
    ActionListener squeezeAction = new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            System.out.println("Ouch!");
        }
    };
    performAction(squeezeAction);
}

public static void performAction(ActionListener method) {
    method.actionPerformed(null); //invoke method
}

      



With lambda expressions (requires JRE 1.8 or higher), this can be simplified to:

public static void main(String[] args) {
    ActionListener squeezeAction = e -> System.out.println("Ouch!");
    performAction(squeezeAction);
}

public static void performAction(ActionListener method) {
    method.actionPerformed(null); //invoke method
}

      

Or as a reference to an existing method:

public class Test {
    public static void main(String[] args) {
        ActionListener squeezeAction = Test::squeeze;
        performAction(squeezeAction);
    }

    public static void sqeeze(ActionEvent e) {
        System.out.println("Ouch!");
    }

    public static void performAction(ActionListener method) {
        method.actionPerformed(null); //invoke method
    }
}

      

0


source







All Articles