用Java编写C#委托 [英] Write C# delegate in java

查看:167
本文介绍了用Java编写C#委托的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在下面的Java版本中编写代码?

How can I write code below in java version?

我读过类似的问题,但是它们令人困惑,他们回答说Java没有像这样的委托功能。另一方面,C#用Java中的委托实现进行了回答,但是与我的情况没有什么相似之处。
我真的希望这个问题清楚。
一个星期以来我一直被困住

I have read similar questions, but they are confusing, they answered that java didn't have delegate feature like c# had, in other hand they answered with their delegate implementation in java, but nothing is similar with my condition. I really hope it's clear on this question. I have been getting stuck since a week

    class Action
    {
        public delegate void ActionDelegate();
        public static ActionDelegate OnAction;

        public void DoAction()
        {
            Console.WriteLine("Action A");
            if (!ReferenceEquals(OnAction, null))
                OnAction();
        }
    }
    class TaskA
    {
        public TaskA()
        {
            Action.OnAction += DoTaskA;
        }
        private void DoTaskA()
        {
            Console.WriteLine("Do Task A");
        }

    }
    class TaskB
    {
        public TaskB()
        {
            Action.OnAction += DoTaskB;
        }
        private void DoTaskB()
        {
            Console.WriteLine("Do Task B");
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            TaskA taskA = new TaskA();
            TaskB task = new TaskB();
            Action action = new Action();
            action.DoAction();
        }
    }

输出:

Action A
Do Task A
Do Task B
Press any keys to continue...


推荐答案

使用项目安全镜在您的类路径中,您将获得对代表和事件的库支持

With the project safety-mirror on your classpath your get library support for delegates and events.

<dependency>
    <groupId>com.github.hervian</groupId>
    <artifactId>safety-mirror</artifactId>
    <version>3.0.0</version>
</dependency>

这里是项目自述文件


  • 乐趣和朋友:没有更多的功能接口:

    Fun.With0Params< String> myFunctionField =" hello world :: trim;

    Fun.With2Params< Boolean,Object,Object> equals = Objects :: equals;

  public void foo(Fun.With1ParamAndVoid<String> printer) throws Exception {
      printer.invoke("hello world);
  }  
  foo(System.out::println);   //This signature match the the Fun defined by method Foo. If it did not, the compiler would emit an error.  

这都是类型安全的:如果方法引用的签名不符合函数引用的定义,则会出现编译时错误。 Fun子类。

It is all type safe: you will get compile time errors if the Method Reference's signature does not match what is defined by the Fun subclass.

  Method m1 = Fun.toMethod(String::isEmpty)
  Method m2 = Fun.<String>toMethod(Class::forName)); // to get overloaded method you must specify parameters in generics  

  assertEquals("isEmpty", Fun.getName(String::isEmpty)); //use Fun's static getName method to get the method name. The Method objects returned from toMethod will not return the correct String.



  • Java中的代表!

  • Delegates in Java!

      Delegate.With1Param<String, String> greetingsDelegate = new Delegate.With1Param<>();
      greetingsDelegate.add(str -> "Hello " + str);
      greetingsDelegate.add(str -> "Goodbye " + str);
    
      DelegateInvocationResult<String> invocationResult = greetingsDelegate.invokeAndAggregateExceptions("Sir");
    
      invocationResult.getFunctionInvocationResults().forEach(funInvRes -> System.out.println(funInvRes.getResult()));
      //prints: "Hello sir" and "Goodbye Sir"
    



  • 事件

  • Events

      //Create a private Delegate. Make sure it is private so only *you* can invoke it.
      private static Delegate.With0Params<String> trimDelegate = new Delegate.With0Params<>();
    
      //Create a public Event using the delegate you just created.
      public static Event.With0Params<String> trimEvent= new Event.With0Params<>(trimDelegate);
    



  • 类型安全方法创建

  • Type safe method creation

      Method m1 = Fun.toMethod(Thread::isAlive)  // Get final method
      Method m2 = Fun.toMethod(String::isEmpty); // Get method from final class
      Method m3 = Fun.toMethod(BufferedReader::readLine); // Get method that throws checked exception
      Method m4 = Fun.<String, Class[]>toMethod(getClass()::getDeclaredMethod); //to get vararg method you must specify parameters in generics
      Method m5 = Fun.<String>toMethod(Class::forName); // to get overloaded method you must specify parameters in generics
      Method m6 = Fun.toMethod(this::toString); //Works with inherited methods
    



  • 免责声明:我是该项目的作者。

    Disclaimer: I am the author of the project.

    这篇关于用Java编写C#委托的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆