Does the Java language have delegate features, similar to how C# has support for delegates?
相关问题
- Delete Messages from a Topic in Apache Kafka
- Jackson Deserialization not calling deserialize on
- How to maintain order of key-value in DataFrame sa
- StackExchange API - Deserialize Date in JSON Respo
- Difference between Types.INTEGER and Types.NULL in
While it is nowhere nearly as clean, but you could implement something like C# delegates using a Java Proxy.
I know this post is old, but Java 8 has added lambdas, and the concept of a functional interface, which is any interface with only one method. Together these offer similar functionality to C# delegates. See here for more info, or just google Java Lambdas. http://cr.openjdk.java.net/~briangoetz/lambda/lambda-state-final.html
Yes & No, but delegate pattern in Java could be thought of this way. This video tutorial is about data exchange between activity - fragments, and it has great essence of delegate sorta pattern using interfaces.
Have you read this :
It doesn't have an explicit
delegate
keyword as C#, but you can achieve similar in Java 8 by using a functional interface (i.e. any interface with exactly one method) and lambda:Every new object of type
SingleFunc
must implementprintMe()
, so it is safe to pass it to another method (e.g.delegate(SingleFunc)
) to call theprintMe()
method.Depending precisely what you mean, you can achieve a similar effect (passing around a method) using the Strategy Pattern.
Instead of a line like this declaring a named method signature:
declare an interface:
For concrete implementations of the method, define a class that implements the behaviour:
Then wherever you would have had a
SomeFunction
delegate in C#, use anISomeBehaviour
reference instead:With anonymous inner classes, you can even avoid declaring separate named classes and almost treat them like real delegate functions.
This should probably only be used when the implementation is very specific to the current context and wouldn't benefit from being reused.
And then of course in Java 8, these do become basically lambda expressions: