1

I have a very good use for having functions as objects in Java, aka the following sort of thing:

Function handle_packet_01 = void handle() {}

I don't want to use Scala because I can't stand the syntax.

Is there any sort of hack that I can apply to the JVM to allow me to do this? How about an Eclipse plugin?

I saw a similar sort of thing for operator overloading in Java, which I am going to install the plugin for too.

4
  • Please read about java 8 api oracle.com/webfolder/technetwork/tutorials/obe/java/… Additionally, You can simulate such approach with creating interface with syntax of handle method. Commented Dec 8, 2015 at 20:31
  • Thanks, I will go and read up about it now. Since this is just for a server, Java 8 is good. Commented Dec 8, 2015 at 20:34
  • @GergelyBacso, there's an Eclipse plugin that lets you use operator overloading in your Java code, so anything's possible, right? Commented Dec 8, 2015 at 20:42
  • Thanks to those who suggested lambdas, they're perfect for this. Commented Dec 8, 2015 at 20:42

1 Answer 1

1

In Java 8 you can reference a member method as following

MyClass::function

EDIT: A more complete example

//For this example I am creating an interface that will serve as predicate on my method
public interface IFilter
{
   int[] apply(int[] data);
}

//Methods that follow the same rule for return type and parameter type from IFilter may be referenced as IFilter
public class FilterCollection
{
    public static int[] median(int[]) {...}
    public int[] mean(int[]) {...}
    public void test() {...}
}

//The class that we are working on and has the method that uses an IFilter-like method as reference
public class Sample
{
   public static void main(String[] args)
   {
       FilterCollection f = new FilterCollection();
       int[] data = new int[]{1, 2, 3, 4, 5, 6, 7};

      //Static method reference or object method reference
      data = filterByMethod(data, FilterCollection::median);
      data = filterByMethod(data, f::mean);

      //This one won't work as IFilter type
      //data = filterByMethod(data, f::test); 
   }

   public static int[] filterByMethod(int[] data, IFilter filter)
   {
       return filter.apply(data);
   }

}

Also take a look at lambda expressions for another example and usage of method reference

Sign up to request clarification or add additional context in comments.

2 Comments

Quick question, what is the type of FIlter::median?
@Lolums I have now provided a better and more complete example.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.