2025-02-11 07:00:05

Java代表?

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


简短的故事:没有。

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.


没有,没有。

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

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


虽然它远没有那么干净,但您可以使用Java代理实现c#委托之类的东西。


我已经在Java中使用反射实现了回调/委托支持。详细信息和工作来源可以在我的网站上找到。

工作原理

有一个名为Callback的原理类和一个名为WithParms的嵌套类。需要回调的API将callback对象作为参数,并在必要时创建callback。使用parms作为方法变量。由于这个对象的许多应用程序都是递归的,所以这非常简单。

由于性能仍然是我的首要任务,我不想被要求创建一个一次性对象数组来保存每次调用的参数——毕竟在大型数据结构中可能有数千个元素,而在消息处理场景中,我们可能会在一秒钟内处理数千个数据结构。

In order to be threadsafe the parameter array needs to exist uniquely for each invocation of the API method, and for efficiency the same one should be used for every invocation of the callback; I needed a second object which would be cheap to create in order to bind the callback with a parameter array for invocation. But, in some scenarios, the invoker would already have a the parameter array for other reasons. For these two reasons, the parameter array does not belong in the Callback object. Also the choice of invocation (passing the parameters as an array or as individual objects) belongs in the hands of the API using the callback enabling it to use whichever invocation is best suited to its inner workings.

因此,WithParms嵌套类是可选的,用于两个目的,它包含回调调用所需的参数对象数组,并提供10个重载invoke()方法(具有1到10个参数),这些方法加载参数数组,然后调用回调目标。

下面是一个使用回调处理目录树中的文件的示例。这是一个初始验证过程,只计算要处理的文件,并确保没有超过预定的最大大小。在本例中,我们只是用API调用内联创建回调。但是,我们将目标方法反射为静态值,这样就不会每次都进行反射。

static private final Method             COUNT =Callback.getMethod(Xxx.class,"callback_count",true,File.class,File.class);

...

IoUtil.processDirectory(root,new Callback(this,COUNT),selector);

...

private void callback_count(File dir, File fil) {
    if(fil!=null) {                                                                             // file is null for processing a directory
        fileTotal++;
        if(fil.length()>fileSizeLimit) {
            throw new Abort("Failed","File size exceeds maximum of "+TextUtil.formatNumber(fileSizeLimit)+" bytes: "+fil);
            }
        }
    progress("Counting",dir,fileTotal);
    }

IoUtil.processDirectory ():

/**
 * Process a directory using callbacks.  To interrupt, the callback must throw an (unchecked) exception.
 * Subdirectories are processed only if the selector is null or selects the directories, and are done
 * after the files in any given directory.  When the callback is invoked for a directory, the file
 * argument is null;
 * <p>
 * The callback signature is:
 * <pre>    void callback(File dir, File ent);</pre>
 * <p>
 * @return          The number of files processed.
 */
static public int processDirectory(File dir, Callback cbk, FileSelector sel) {
    return _processDirectory(dir,new Callback.WithParms(cbk,2),sel);
    }

static private int _processDirectory(File dir, Callback.WithParms cbk, FileSelector sel) {
    int                                 cnt=0;

    if(!dir.isDirectory()) {
        if(sel==null || sel.accept(dir)) { cbk.invoke(dir.getParent(),dir); cnt++; }
        }
    else {
        cbk.invoke(dir,(Object[])null);

        File[] lst=(sel==null ? dir.listFiles() : dir.listFiles(sel));
        if(lst!=null) {
            for(int xa=0; xa<lst.length; xa++) {
                File ent=lst[xa];
                if(!ent.isDirectory()) {
                    cbk.invoke(dir,ent);
                    lst[xa]=null;
                    cnt++;
                    }
                }
            for(int xa=0; xa<lst.length; xa++) {
                File ent=lst[xa];
                if(ent!=null) { cnt+=_processDirectory(ent,cbk,sel); }
                }
            }
        }
    return cnt;
    }

This example illustrates the beauty of this approach - the application specific logic is abstracted into the callback, and the drudgery of recursively walking a directory tree is tucked nicely away in a completely reusable static utility method. And we don't have to repeatedly pay the price of defining and implementing an interface for every new use. Of course, the argument for an interface is that it is far more explicit about what to implement (it's enforced, not simply documented) - but in practice I have not found it to be a problem to get the callback definition right.

定义和实现一个接口并不是那么糟糕(除非你像我一样分发applet,避免创建额外的类实际上很重要),但是当你在一个类中有多个回调时,这才是真正的亮点。不仅被迫将它们分别推到一个单独的内部类中增加了部署应用程序的开销,而且编程非常乏味,所有的样板代码实际上只是“噪音”。


你读过这篇文章吗?

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.


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

  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代码。


不,但它内部有相似的行为。

在c#中,委托用于创建一个单独的入口点,它们的工作原理很像函数指针。

在java中没有函数指针,但是在内部java需要做同样的事情来实现这些目标。

例如,在Java中创建线程需要一个类扩展Thread或实现Runnable,因为类对象变量可以用作内存位置指针。


根据您的意思,您可以使用策略模式达到类似的效果(传递一个方法)。

而不是像这样的一行声明一个命名方法签名:

// C#
public delegate void SomeFunction();

声明一个接口:

// Java
public interface ISomeBehaviour {
   void SomeFunction();
}

对于方法的具体实现,定义一个实现行为的类:

// Java
public class TypeABehaviour implements ISomeBehaviour {
   public void SomeFunction() {
      // TypeA behaviour
   }
}

public class TypeBBehaviour implements ISomeBehaviour {
   public void SomeFunction() {
      // TypeB behaviour
   }
}

然后在c#中使用SomeFunction委托的地方,使用ISomeBehaviour引用:

// C#
SomeFunction doSomething = SomeMethod;
doSomething();
doSomething = SomeOtherMethod;
doSomething();

// Java
ISomeBehaviour someBehaviour = new TypeABehaviour();
someBehaviour.SomeFunction();
someBehaviour = new TypeBBehaviour();
someBehaviour.SomeFunction();

使用匿名内部类,您甚至可以避免声明单独的命名类,几乎可以将它们视为真正的委托函数。

// Java
public void SomeMethod(ISomeBehaviour pSomeBehaviour) {
   ...
}

...

SomeMethod(new ISomeBehaviour() { 
   @Override
   public void SomeFunction() {
      // your implementation
   }
});

这可能只应该在实现非常特定于当前上下文并且不会从重用中受益时使用。

当然,在Java 8中,这些基本变成了lambda表达式:

// Java 8
SomeMethod(() -> { /* your implementation */ });

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

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


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


是或否,但是Java中的委托模式可以这样考虑。本视频教程讲的是活动片段之间的数据交换,具有使用接口的委托排序模式的精髓。


它不像c#那样有显式的委托关键字,但你可以在Java 8中通过使用函数接口(即任何只有一个方法的接口)和lambda来实现类似的功能:

private interface SingleFunc {
    void printMe();
}

public static void main(String[] args) {
    SingleFunc sf = () -> {
        System.out.println("Hello, I am a simple single func.");
    };
    SingleFunc sfComplex = () -> {
        System.out.println("Hello, I am a COMPLEX single func.");
    };
    delegate(sf);
    delegate(sfComplex);
}

private static void delegate(SingleFunc f) {
    f.printMe();
}

每个SingleFunc类型的新对象都必须实现printMe(),因此将它传递给另一个方法(例如委托(SingleFunc))来调用printMe()方法是安全的。


不,Java没有这个惊人的特性。但是您可以使用观察者模式手动创建它。这里有一个例子: 用java编写c#委托


所描述的代码提供了c#委托的许多优点。方法,无论是静态的还是动态的,都可以以统一的方式处理。通过反射调用方法的复杂性降低了,而且代码是可重用的,因为在用户代码中不需要额外的类。请注意,我们调用的是invoke的另一个方便版本,其中只带一个参数的方法可以在不创建对象数组的情况下被调用。

  class Class1 {
        public void show(String s) { System.out.println(s); }
    }

    class Class2 {
        public void display(String s) { System.out.println(s); }
    }

    // allows static method as well
    class Class3 {
        public static void staticDisplay(String s) { System.out.println(s); }
    }

    public class TestDelegate  {
        public static final Class[] OUTPUT_ARGS = { String.class };
        public final Delegator DO_SHOW = new Delegator(OUTPUT_ARGS,Void.TYPE);

        public void main(String[] args)  {
            Delegate[] items = new Delegate[3];

            items[0] = DO_SHOW .build(new Class1(),"show,);
            items[1] = DO_SHOW.build (new Class2(),"display");
            items[2] = DO_SHOW.build(Class3.class, "staticDisplay");

            for(int i = 0; i < items.length; i++) {
                items[i].invoke("Hello World");
            }
        }
    }

通过类路径上的安全镜像,你可以得到类似c#委托和事件的东西。

来自项目README的例子:

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"

事件

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

看看这个SO的答案。