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,避免创建额外的类实际上很重要),但是当你在一个类中有多个回调时,这才是真正的亮点。不仅被迫将它们分别推到一个单独的内部类中增加了部署应用程序的开销,而且编程非常乏味,所有的样板代码实际上只是“噪音”。
其他回答
所描述的代码提供了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");
}
}
}
是或否,但是Java中的委托模式可以这样考虑。本视频教程讲的是活动片段之间的数据交换,具有使用接口的委托排序模式的精髓。
简短的故事:没有。
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)
不,但它内部有相似的行为。
在c#中,委托用于创建一个单独的入口点,它们的工作原理很像函数指针。
在java中没有函数指针,但是在内部java需要做同样的事情来实现这些目标。
例如,在Java中创建线程需要一个类扩展Thread或实现Runnable,因为类对象变量可以用作内存位置指针。
推荐文章
- Java 8接口方法中不允许“同步”的原因是什么?
- 如何找到Java堆大小和内存使用(Linux)?
- 使用Enum实现单例(Java)
- RabbitMQ与通道和连接之间的关系
- buildSessionFactory()配置方法在Hibernate中已弃用?
- Spring MVC -如何获得所有的请求参数在一个地图在Spring控制器?
- 如何在Java中按两个字段排序?
- 文件之间的差异。路径中的分隔符和斜杠
- 在方法参数中使用NotNull注释
- Spring MVC中处理可选参数的@RequestParam
- Tomcat:如何查找正在运行的Tomcat版本?
- “java”、“javaw”和“javaws”之间有什么区别?
- 将Date对象转换为日历对象
- 在Java中保存最后N个元素的大小有限的队列
- 如何运行一个类从Jar不是主类在其清单文件