Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

What follows is code that won't compile, but its really the only way I can think of describing 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 across here is that a new instance of Class0 is initialized with an anonymous function. The instance is then passed to an instance of Library.

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 constructed from the constructor method and sets the function to the action field, it remains uncalled but stored for later. action() calls the function passed into the constructor.

Library.java

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

For the most part Library.java is out of my control, it is an conduit for a third-party library. go calls the stored function of the instance object, declared in main, through its action method.

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
278 views
Welcome To Ask or Share your Answers For Others

1 Answer

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

It appears that you want to implement a callback interface.

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

Here is 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);
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...