R
R
ramntry2013-01-03 21:18:17
Java
ramntry, 2013-01-03 21:18:17

What features does modern Java provide for emulating .NET delegates?

The existence of the Runnable, Callable<V> interfaces is known - they are not interesting because either completely (in the first case) or almost completely (with the exception of the return value type in the second case) fix the signature of the method that we would like to wrap in a delegate.

The possibilities of Java in the field of creating inner classes, anonymous classes, and closures of methods of such classes are known. But this is not quite what we would like - there are no honest lambdas, no delegates in the .NET sense (well, there are no function pointers, honest templates, and other things that solve the problem in C ++). You need something deader than this .

What does the habrosociety know about this?

Answer the question

In order to leave comments, you need to log in

4 answer(s)
O
orionll, 2013-01-07
@orionll

We use this approach:

interface Function0<T>
{
   T execute();
}

interface Function1<T, R>
{
    T execute(R arg1);
}

interface Function2<T, R1, R2>
{
    T execute(R1 arg1, R2 arg2);
}

interface Function3<T, R1, R2, R3>
{
    T execute(R1 arg1, R2 arg2, R3 arg3);
}

...

C
cyberorg, 2013-01-04
@kyberorg

At the moment, it is known that Java 8 will have lambdas.
As for the functionality of delegates, most likely this will not happen in the foreseeable future.
I don't fully understand the meaning of delegates in C#. If this is passing a method as an argument, then perhaps java.reflection (for example, the forName method) will help.

M
Maxim Moseychuk, 2014-01-24
@fshp

Discover Scala

A
avpmk, 2014-02-18
@avpmk

Java 8 has (in 2012 there were already (maybe I don’t know before)) lambdas, functional interfaces and method references.
Assign a functional interface (any interface that has only one abstract method) a lambda expression or a methodReference with an appropriate signature, other code calls that single method..
Like this:
java 8 (instance method)

Block<String> aFunctionalInterface = System.out::println;
Arrays.asList("А", "B", "C", "D", "E").forEach(aFunctionalInterface);

Predicate<String> p = "Строка"::equalsIgnoreCase;
System.out.println(p.test("СТРОКА"));
System.out.println(p.test("строкА"));
System.out.println(p.test("Другая строка"));

java 8 (static method)
System.out.println(
    Arrays.asList("А", "Bb", "Ccc", "Ddddddddddddd", "Eeee")
    .stream()
    .map(s -> s.length())
    .reduce(Math::max)
    .get()
);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question