Question

Is it possible through some method to assign a function to a variable in Java, like in PHP or JavaScript?

...Or does this area works on a different way when it comes to Java?

Was it helpful?

Solution

In Java you have Method and MethodHandles which can invoke a method via reflection but that is not supported in the language yet.

In Java 8, you will be able to use references to methods.

OTHER TIPS

In today's java, no you can't.

The nearest you have is the interface : you don't store a function but the implementation of an interface defining the wanted function.

A typical example is the implementation of the Comparator interface :

Comparator<ProductSearchResult> c = new Comparator<ProductSearchResult>() {
    public int compare(ProductSearchResult result1, ProductSearchResult result2) {
        return result1.product.getRsId().compareTo(result2.product.getRsId());
    }
};
Collections.sort(groupResults, c); // I pass a function, wrapped in my Comparator implementation

The nearest you have are inner classes combined with interfaces. These can carry not only one but many functions (methods) that can be delegated back to the master class methods if preferred. But this solution may easily be too heavyweight:

class Main {

   interface X { 
     void doX();
   }

   class Ref1 implements X {
     void doX() { doA(); };
   }

   class Ref2 implements X {
     void doX() { doB(); };
   }

   void doA() {  };
   void doB() {  };

   void demo() {
      X x = new Ref1();
      x.doX();
   }
}

This simulates something similar to Lambdas ... (you'll need a little more casting if you use anything other than Strings, but I'm keeping the example brief) ...

public class MyTest {

    public static void main(String[] args) {

        Lambda l = new Lambda() { public Object func(Object x) 
                                    { return "Hello " + x; } 
                                };

        System.out.println(l.func("Bob"));

        System.out.println(nowTryFromMethod(l));

        System.out.println((new Lambda() { public Object func(Object x) 
                                             { return "Goodbye " + x; }
                                         }).func("Harry"));
    }

    private static Object nowTryFromMethod(Lambda l) {
            return l.func("Jerry");
    }
}

class Lambda {

    public Object func(Object x) { return null; }
}

Output:

Hello Bob
Hello Jerry
Goodbye Harry

Update

Java supports reference to functions which is called Lambda from version 1.8

Java does NOT support that.

However, you can do that in JVM-Languages very comfortably, e.g. in Groovy.

Or you take a look at the command-pattern.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top