Java语言是否具有委托特性,类似于c#对委托的支持?
当前回答
Java没有委托,并以此为傲:)。从我在这里读到的内容中,我发现了两种伪造委托的方法: 1. 反射; 2. 内部类
倒影是缓慢的!内部类不包括最简单的用例:排序函数。我不想深入讨论细节,但是使用内部类的解决方案基本上是为按升序排序的整数数组创建一个包装器类,为按降序排序的整数数组创建一个类。
其他回答
Java没有委托,并以此为傲:)。从我在这里读到的内容中,我发现了两种伪造委托的方法: 1. 反射; 2. 内部类
倒影是缓慢的!内部类不包括最简单的用例:排序函数。我不想深入讨论细节,但是使用内部类的解决方案基本上是为按升序排序的整数数组创建一个包装器类,为按降序排序的整数数组创建一个类。
你读过这篇文章吗?
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.
通过类路径上的安全镜像,你可以得到类似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的答案。
我已经在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,避免创建额外的类实际上很重要),但是当你在一个类中有多个回调时,这才是真正的亮点。不仅被迫将它们分别推到一个单独的内部类中增加了部署应用程序的开销,而且编程非常乏味,所有的样板代码实际上只是“噪音”。
虽然它远没有那么干净,但您可以使用Java代理实现c#委托之类的东西。
推荐文章
- 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不是主类在其清单文件