2025-02-11 07:00:05

Java代表?

Java语言是否具有委托特性,类似于c#对委托的支持?


当前回答

Java没有委托,并以此为傲:)。从我在这里读到的内容中,我发现了两种伪造委托的方法: 1. 反射; 2. 内部类

倒影是缓慢的!内部类不包括最简单的用例:排序函数。我不想深入讨论细节,但是使用内部类的解决方案基本上是为按升序排序的整数数组创建一个包装器类,为按降序排序的整数数组创建一个类。

其他回答

不,但是它们可以通过代理和反射来伪装:

  public static class TestClass {
      public String knockKnock() {
          return "who's there?";
      }
  }

  private final TestClass testInstance = new TestClass();

  @Test public void
  can_delegate_a_single_method_interface_to_an_instance() throws Exception {
      Delegator<TestClass, Callable<String>> knockKnockDelegator = Delegator.ofMethod("knockKnock")
                                                                   .of(TestClass.class)
                                                                   .to(Callable.class);
      Callable<String> callable = knockKnockDelegator.delegateTo(testInstance);
      assertThat(callable.call(), is("who's there?"));
  }

这种习惯用法的好处在于,您可以在创建委托器时验证委托方法是否存在,并具有所需的签名(不幸的是,在编译时不存在,尽管FindBugs插件在这里可能会有所帮助),然后安全地使用它来委托给各种实例。

有关更多测试和实现,请参阅github上的karg代码。

简短的故事:没有。

Introduction The newest version of the Microsoft Visual J++ development environment supports a language construct called delegates or bound method references. This construct, and the new keywords delegate and multicast introduced to support it, are not a part of the JavaTM programming language, which is specified by the Java Language Specification and amended by the Inner Classes Specification included in the documentation for the JDKTM 1.1 software. It is unlikely that the Java programming language will ever include this construct. Sun already carefully considered adopting it in 1996, to the extent of building and discarding working prototypes. Our conclusion was that bound method references are unnecessary and detrimental to the language. This decision was made in consultation with Borland International, who had previous experience with bound method references in Delphi Object Pascal. We believe bound method references are unnecessary because another design alternative, inner classes, provides equal or superior functionality. In particular, inner classes fully support the requirements of user-interface event handling, and have been used to implement a user-interface API at least as comprehensive as the Windows Foundation Classes. We believe bound method references are harmful because they detract from the simplicity of the Java programming language and the pervasively object-oriented character of the APIs. Bound method references also introduce irregularity into the language syntax and scoping rules. Finally, they dilute the investment in VM technologies because VMs are required to handle additional and disparate types of references and method linkage efficiently.

我知道这篇文章很旧了,但是Java 8增加了lambdas和函数接口的概念,即任何接口都只有一个方法。它们一起提供了与c#委托类似的功能。查看这里获得更多信息,或者只是谷歌Java Lambdas。 http://cr.openjdk.java.net/~briangoetz/lambda/lambda-state-final.html

没有,没有。

你可以通过使用反射来获得你可以调用的Method对象来达到同样的效果,另一种方法是创建一个带有单个“invoke”或“execute”方法的接口,然后实例化它们来调用你感兴趣的方法(即使用匿名内部类)。

你可能还会发现这篇文章很有趣/有用:一个Java程序员看c#委托(@blueskyprojects.com)

你读过这篇文章吗?

Delegates are a useful construct in event-based systems. Essentially Delegates are objects that encode a method dispatch on a specified object. This document shows how java inner classes provide a more generic solution to such problems. What is a Delegate? Really it is very similar to a pointer to member function as used in C++. But a delegate contains the target object alongwith the method to be invoked. Ideally it would be nice to be able to say: obj.registerHandler(ano.methodOne); ..and that the method methodOne would be called on ano when some specific event was received. This is what the Delegate structure achieves. Java Inner Classes It has been argued that Java provides this functionality via anonymous inner classes and thus does not need the additional Delegate construct.

obj.registerHandler(new Handler() {
        public void handleIt(Event ev) {
            methodOne(ev);
        }
      } );

At first glance this seems correct but at the same time a nuisance. Because for many event processing examples the simplicity of the Delegates syntax is very attractive. General Handler However, if event-based programming is used in a more pervasive manner, say, for example, as a part of a general asynchronous programming environment, there is more at stake. In such a general situation, it is not sufficient to include only the target method and target object instance. In general there may be other parameters required, that are determined within the context when the event handler is registered. In this more general situation, the java approach can provide a very elegant solution, particularly when combined with use of final variables:

void processState(final T1 p1, final T2 dispatch) { 
  final int a1 = someCalculation();

  m_obj.registerHandler(new Handler() {
    public void handleIt(Event ev) {
     dispatch.methodOne(a1, ev, p1);
    }
  } );
}

final * final * final Got your attention? Note that the final variables are accessible from within the anonymous class method definitions. Be sure to study this code carefully to understand the ramifications. This is potentially a very powerful technique. For example, it can be used to good effect when registering handlers in MiniDOM and in more general situations. By contrast, the Delegate construct does not provide a solution for this more general requirement, and as such should be rejected as an idiom on which designs can be based.