Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delegate method calling in Java

Tags:

java

android

In Java: What is the best way to pass a method from one object to another so that it can be called at a later time by the second object?

I come from an ActionScript background where it is as easy to pass around references to methods as it is to pass around references to variables but this seems to be much more difficult in Java. The first few links I found flat out say it is not possible (and it may have been at the time of their posting), but then I found http://www.javacamp.org/javavscsharp/delegate.html which details how this can be accomplished.

My issue with using Javacamp's example is the string based reference to the method. Methods get renamed all the time and a string reference will only complain once you actually run that function runtime as opposed to compile time for a proper explicit link.

Is there no way to do this with proper explicit links to the method you want the other class to execute?

Model of what I am hoping to accomplish:

  1. Player clicks an upgrade button on Activity1 > Activity1 passes upgrade method to a new confirmation activity
  2. Player clicks "Yes" > Confirmation activity calls upgrade method passed in from Activity1
  3. OR: Player clicks "No" > Confirmation Activity closes

EDIT: To be clear I am not looking for a static method solution as that would require my Confirmation activity to hold many lines of logic for which static method to call. The Confirmation activity will be used all over my application: a simple "Are you sure you want to X?" -Yes -No, if yes execute X

I am currently looking at implementing onActivityResult to avoid this issue but that will be more logic than I like for this kind of issue.

like image 232
Currence Avatar asked Sep 12 '14 01:09

Currence


People also ask

What is delegate method in Java?

Delegation is simply passing a duty off to someone/something else. Delegation can be an alternative to inheritance. Delegation means that you use an object of another class as an instance variable, and forward messages to the instance.

What is method delegation?

A delegate method is a method that the delegate object is expected to implement. Some delegate methods are required, while some are not. In IOS, most delegates are expected to conform to an Objective-C protocol; the protocol declaration will tell you which methods are optional and which are required.

Do we have delegates in Java?

Java 8 has a feature quite like delegates. It's called lambdas. @tbodt to be more correct, Java 8 has a feature quite like delegates. It's called functional interfaces.

What's the difference between inheritance and delegation?

Delegation is an alternative to inheritance for reusing code among multiple classes. Inheritance uses the IS-A relationship for re-use; delegation uses the HAS-A reference relationship to do the same. Inheritance and delegation have the same kind of relationship that, say, Aspirin and Tylenol, have.


2 Answers

you can use interfaces like this:

public interface MyMethod {
    public void method();
}


public class FirtObject{

    private SecondObject ob;

    public void tellSecondObjectExecuteLater(){
        ob.executeLater( new MyMethod() { 
          public void method(){System.out.println("duh Method");} });
    }
}

public class SecondObject {

    private MyMethod myMth;

    public void executeLater(MyMethod mth){
        myMth = mth;
    }

    public void executeNow(){
        myMth.method();
    }
}

does this solve your problem?

like image 64
jcstar Avatar answered Sep 28 '22 05:09

jcstar


The typical way to pass methods is to use an Interface and Anonymous Inner Classes. In order to maintain static typing an Interface is used to declare the method signature and typing information. The caller can use either a concrete implementation of that interface as a normal class or using Anonymous Inner Classes for quick class creation. I'll use standard Java SDK classes to illustrate:

interface Comparator<T> {
    public int compare( T a, T b); 
}

class SpecialCollection<T> {
    public void sort( Comparator<T> comparator ) {...} 
}

public class SomeClient {
    public void doSomething( SpecialCollection<SpecialObj> collection ) {

        collection.sort( new Comparator<SpecialObj>() {
           public int compare( SpecialObject a, SpecialObject b ) {
               // some implementation
           }
        } );
    }
}

The above is an example of a strategy pattern. The thing about the strategy pattern (and passing callback methods like in Javascript). The author has to plan for those types of extensions. The author has to predict up front where he/she wants you to extend. And it just happens it's cleanest if you use Interfaces.

However, pure delegation doesn't have to have always involve Interfaces. You can pass concrete classes, since Java can always pass a subclass that overrides various methods of that class to change what method or code will be invoked. For example in Java InputStream/OutputStream are abstract classes and you typically pass subclass instances to the methods.

like image 40
chubbsondubs Avatar answered Sep 28 '22 07:09

chubbsondubs