Java funziona come Oggetti


Ho un ottimo uso per avere funzioni come oggetti in Java, ovvero il seguente genere di cose:

Function handle_packet_01 = void handle() {}

Non voglio usare Scala perché non sopporto la sintassi.

C'è qualche tipo di hack che posso applicare alla JVM per permettermi di farlo? Che ne dici di un plugin Eclipse?

Ho visto un tipo di cosa simile per il sovraccarico dell'operatore in Java, che installerò anche per il plugin.

Author: Lolums, 2015-12-08

1 answers

In Java 8 è possibile fare riferimento a un metodo membro come segue

MyClass::function

MODIFICA: Un esempio più completo

//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);
   }

}

Date anche un'occhiata a espressioni lambda per un altro esempio e l'utilizzo del riferimento al metodo

 1
Author: KuramaYoko, 2015-12-09 16:59:31