简体   繁体   English

Java中C#匿名方法的等价物?

[英]Equivalent of C# anonymous methods in Java?

In C# you can define delegates anonymously (even though they are nothing more than syntactic sugar). 在C#中,您可以匿名定义委托(即使它们只不过是语法糖)。 For example, I can do this: 例如,我可以这样做:

public string DoSomething(Func<string, string> someDelegate)
{
     // Do something involving someDelegate(string s)
} 

DoSomething(delegate(string s){ return s += "asd"; });
DoSomething(delegate(string s){ return s.Reverse(); });

Is it possible to pass code like this in Java? 是否可以在Java中传递这样的代码? I'm using the processing framework, which has a quite old version of Java (it doesn't have generics). 我正在使用处理框架,它有一个相当旧版本的Java(它没有泛型)。

Pre Java 8: 前Java 8:

The closest Java has to delegates are single method interfaces. 最接近Java的代理是单方法接口。 You could use an anonymous inner class. 您可以使用匿名内部类。

interface StringFunc {
   String func(String s);
}

void doSomething(StringFunc funk) {
   System.out.println(funk.func("whatever"));
}

doSomething(new StringFunc() {
      public String func(String s) {
           return s + "asd";
      }
   });


doSomething(new StringFunc() {
      public String func(String s) {
           return new StringBuffer(s).reverse().toString();
      }
   });

Java 8 and above: Java 8及以上版本:

Java 8 adds lambda expressions to the language. Java 8将lambda表达式添加到该语言中。

    doSomething((t) -> t + "asd");
    doSomething((t) -> new StringBuilder(t).reverse().toString());

Not exactly like this but Java has something similar. 不完全是这样,但Java有类似的东西。

It's called anonymous inner classes. 它被称为匿名内部类。

Let me give you an example: 让我给你举个例子:

DoSomething(new Runnable() {
   public void run() {
       // "delegate" body
   }
});

It's a little more verbose and requires an interface to implement, but other than that it's pretty much the same thing 它有点冗长,需要一个接口来实现,但除此之外它几乎是一样的

Your example would look like this in Java, using anomymous inner classes: 您的示例在Java中看起来像这样,使用不同的内部类:

interface Func {
    String execute(String s);
}

public String doSomething(Func someDelegate) {
    // Do something involving someDelegate.execute(String s)
}

doSomething(new Func() { public String execute(String s) { return s + "asd"; } });
doSomething(new Func() { public String execute(String s) { return new StringBuilder(s).reverse().toString(); } } });

Is it possible to pass code like this in Java? 是否可以在Java中传递这样的代码? I'm using the processing framework, which has a quite old version of Java (it doesn't have generics). 我正在使用处理框架,它有一个相当旧版本的Java(它没有泛型)。

Since the question asked about the Processing-specific answer, there is no direct equivalent. 由于问题是关于特定于处理的答案,因此没有直接的等价物。 But Processing uses the Java 1.4 language level, and Java 1.1 introduced anonymous inner classes, which are a rough approximation. 但是Processing使用Java 1.4语言级别,Java 1.1引入了匿名内部类,这是一个粗略的近似。

For example : 例如 :

public class Delegate
{
    interface Func
    {
        void execute(String s);
    }

    public static void doSomething(Func someDelegate) {
        someDelegate.execute("123");
    }

    public static void main(String [] args)
    {

        Func someFuncImplementation = new Func() 
        {
            @Override
            public void execute(String s) {
                System.out.println("Bla Bla :"  + s);
            }
        };

        Func someOtherFuncImplementation = new Func() 
        {
            @Override
            public void execute(String s) {
                System.out.println("Foo Bar:"  + s);
            }
        };


        doSomething(someFuncImplementation);
        doSomething(someOtherFuncImplementation);
    }
}

Output : 输出:

Bla Bla :123 Bla Bla:123

Foo Bar:123 Foo Bar:123

You have all forgotten here that a C# delegate first of all - is thread safe . 你们都忘记了首先是C#委托 - 是线程安全的 These examples are just for a single thread App.. 这些示例仅适用于单线程App ..

Most of the contemporary Apps are written on multithreaded concept.. So no one answer is the answer. 大多数现代应用程序都是用多线程概念编写的。所以没有一个答案是答案。

There is not an equivalent in Java Java中没有相应的东西

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM