I'm reading about Functional Interfaces in Java in this tutorial
Here is the specific code that is bothering me:
public interface FunctionalInterfaceTest{
void display();
}
//Test class to implement above interface
public class FunctionInterfaceTestImpl {
public static void main(String[] args){
//Old way using anonymous inner class
FunctionalInterfaceTest fit = new FunctionalInterfaceTest(){
public void display(){
System.out.println("Display from old way");
}};
fit.display();//outputs: Display from old way
//Using lambda expression
FunctionalInterfaceTest newWay = () -> {System.out.println("Display from new Lambda Expression");}
newWay.display();//outputs : Display from new Lambda Expression
}
}
I don't understand. What is the point of having a function called display(). It doesn't do anything and is never defined. Yes I understand that when you call the single method in a Functional Interface, it executes the code in the lambda expression that was created in it.
But here's my question; if all functional interfaces essentially just run lambda expressions, then why not just save us the time of naming the single method, and just make it permanently exe()? What is the point of offering the Functional Interface syntax and customization if it adds almost nothing. A far better syntax for me would be:
#FunctionalInterface MyInterface
MyInterface mine = () -> {System.out.print("Mine!!")}
mine.exe();
This is much more standard, shorter and easier to understand.
Is this a brilliant idea or am I missing something?
What is the point of having a function called display(). It doesn't do anything and is never defined.
It's still an interface at heart, and it's still subject to the same wonky rules that an interface would be if you weren't using lambdas.
The display method could be defined on a concrete class in the exact same manner...
public class Concrete implements FunctionalInterfaceTest {
#Override
public void display() {
System.out.println("Displayed! W00t!");
}
}
...and we would have done the exact same amount of work: we have an interface which only generates side effects. This is not desirable.
The real power of this comes in when you want to actually do pure operations on objects or primitives, but you don't want to define concrete classes just to specify what those operations actually are.
Let's suppose we wanted a functional interface to give us the difference of two Numbers.
#FunctionalInterface
public interface NumberAdder<T extends Number> {
T result (T firstValue, T secondValue);
}
I can then use it in this manner:
NumberAdder<Integer> numberAdder = (x, y) -> x + y;
NumberAdder<Long> longAdder = (x, y) -> x + y;
// From (x, y) -> x.add(y);, the below is shortened to a method reference
NumberAdder<BigInteger> bigIntAdder = BigInteger::add;
It's by and large syntactic sugar for the subclassing - anonymous or not - that would have to happen with the interface. Instead, I can define the contract once and define the behavior in whatever scenario/context I need it to be in.
System.out.println(numberAdder.result(10, 20));
System.out.println(longAdder.result(172893791273L, 979789123L));
System.out.println(bigIntAdder.result(BigInteger.valueOf(172917298179821L), BigInteger.valueOf(17232891L)));
It is still your responsibility to define the behavior. You could easily write this:
NumberAdder<BigInteger> bigIntAdder2 = BigInteger::divide;
...and that would still be just fine with the interface. You need to be careful that your intended use isn't abused when it comes time to actually implement it.
Don't treat lambdas as anything that they aren't. By and large, you're replacing anonymous classes with a lambda expression. If you want to get fancy with it you're more than welcome to, but don't assume that every functional interface follows the same conventions between them.
=== Conclusion ====
found a good read at https://softwareengineering.stackexchange.com/a/149569 which states
Current GC algorithms are actually optimized for creating many many small objects that are short lived,
So I think using anonymous inner class a lot in project would not be a big deal regarding to performance*
========================================================================
Because function is not the first class citizen in current Java(Java7), using anonymous inner class seems the only way to implement full async application.
I know it will bring larger memory footprint and burden garbage collector in some extent, but I don't know how serious it could be? Recently my colleague argued with me because my code was written in functional style by leveraging anonymous inner class, his objection was all about performance. Though I don't agree, I can't cite any example to prove myself. I know groovy is implementing closure all using anonymous class, but groovy does have poorer performance than java(of course anonymous should only take part of responsibility, as groovy heavily uses reflection as well).
so I wonder in real world, is there any project dropping anonymous class just because performance? how about UI framework like swing? Is it using anonymous class massively?
without anonymous, I can't imagine how to implement async elegantly in java. our project already uses a very ugly way to make class method work as function pointer. I hate that much and want to convince people anonymous class is the right way to go.
My Example:
// basically, I use Completion interface to make normal java methods work in async manner
public interface Completion {
void success();
void fail(String reason);
}
void methodA(Completion completion) {
do_some_business_by_calling_remote_service ....
when remote_service_ack_success:
completion.success();
else:
completion.fail(remote_service_error);
}
void methodB() {
methodA(new Completion() {
public void success() {
continue to do something;
}
public void fail(String err) {
handle error
}
});
}
There's basically two issues here, neither of them really have to do with the anonymous aspect. Anonymous classes aren't really any different than regular inner classes except that they don't have a name. An anonymous inner class gets compiled to a regular inner class, which in turn is still not really any different from a static nested class.
Issue 1 is that since they are inner, they keep a reference to the enclosing class:
class Outer {
interface Inner {}
Inner inner = new Inner() {
{
System.out.println(Outer.this);
}
};
}
This is not so much an issue and most of the time it's desired because you are doing something functional and want to use the outer instance's members inside the inner class. But it could create problems since as long as the inner class is alive, the outer class can't be garbage collected.
Issue 2 is that indeed they are an object so indeed your methodB is creating a new one each time it's called.
The obvious solution is just to create it once:
class MyProcess {
final Completion myCompletion = new Completion() {
#Override
public void success() {}
#Override
public void fail(String err) {}
}
void methodA(Completion c) {}
void methodB() {
methodA(myCompletion);
}
}
It seems like what you like is the syntax though and there's not really a solution to keep the syntax and not create an object at the same time.
My personal opinion: if you aren't calling this method a lot, I agree the syntax can be nice and clear. If you are calling it a lot, switch to a single object because you are crowding memory space. If it gets called 1000 times, that's 1000 objects. Object size differs by platform, but it's typically a minimum 8 or 16 bytes + a pointer to the outer instance. That's not a huge impact but it could, for example, prompt garbage collection to run which can cause subtle stalling.
By the way, I was thinking about this again and thought of the following idea:
Completion myLazyCompletion;
void methodB() {
methodA(myLazyCompletion != null ? myLazyCompletion :
(myLazyCompletion = new Completion() {
// overrides
})
);
}
I would say don't do that, but I thought it was interesting. : )
I've just read through the chapter on method-local inner classes in the SCJP book, and I'm really struggling to think of any practical use for them.
I've always been under the impression, that methods should be as small and specific to their task as possible (Orthogonality IIRC), so introducing even the simplest inner class would create heft and unwieldy methods.
Can anyone suggest a good practical usage for method local inner classes? So far it feels as if I might have to understand them purely for passing the exam, and not for use in everyday coding.
Cheers
In most cases (e.g. for action listeners, runnables and such) you would use anonymous classes instead of method-local named classes.
But there is one thing which named classes can do and anonymous classes can't: implementing more than one interface, or extending a class and interfaces, too. Also, you can create more than one object of this class (without using a loop).
I'd say that better encapsulation is the benefit.
Method local inner classes are useful when you are trying to do "functional" operations, or passing code to another object to be called later. In most cases classes like these are only called or used once, so there is no need to define it somewhere else and force the reader to go hunting for it. Future versions of Java are likely to replace most use cases for these types of inner classes with "closures".
Common cases are when you are writing an event listener that calls some other method or starting a new thread.
Local classes allows to take logic out of the parent class and objectify it. This removes functionality from where it doesn't belong and puts it into its own class. But what if this new object is only needed for a short time, only for the duration of a single block of code? Well, that's where a local class fits in.
I think of Runnable implementation passed to Thread:
Thread t = new Thread(new Runnable() {
void run() {
...
}
});
This is anonymous class, and any anonymous class is inner as well.
The local classes (method local inner classes) are rarely used. It can be useful when any repeated functionality is required inside a method and if we are NOT interested to create class level method (may be because this functionality we may not require outside of method) for example, lets assume sum & mul methods are repeatedly require in our code (any particular method), one way to create a class level methods and call them whenever required, but what if these methods no longer required outside this method, in this case we may think of creating a local inner class and access its sum method whenever required only within that method, below example
class Outer {
public void calculations() {
class Inner {
public int sum(int x, int y) {
System.out.println("sum : " + (x+y));
return x+y;
}
public int mul(int x, int y) {
System.out.println("multiplication : " + (x*y));
return x*y;
}
}
Inner i= new Inner();
//some code...
i.sum(10, 20);
//some code...etc
i.mul(30, 40);
i.mul(14, 12);
i.sum(10000, 20000);
//some other code...
}
}
public class TestClass {
public static void main(String[] args) {
new Outer().calculations();
}
}
This is something like Reflection where you can call a method simply by its name, and not a precompiled pointer to it.
Like in JavaScript you can:
var fun = function(){ alert("Hello World!"); }
fun();
Is something like that possible in Java/J2ME? How?
If you want an interpreter for j2me, you could check out Hecl: http://www.hecl.org
You definitely can't do most of the 'fancy' things you can do in normal Java in J2ME. The alternative is a series of if/elseif's that then call the function you want, but you still have to know that ahead of time so that you can write the code that does that.
One way to imitate this functionality is to create a strategy class.
interface Function
{
Object call(Object[] arguments);
}
To do what you suggested, simply do the following (a bit more verbose, as Java typically is):
static class Fun implements Function
{
public Object call(Object[] arguments)
{
System.out.println("Hello, world");
return null;
}
}
Function fun = new Fun();
fun.call(null);
Depending on the situation, you might be able to use better types or generics instead of Object and Object[] (in this case, I used them for maximum flexibility, but they don't give you much in the way of type checking so it's not ideal).
For more information, look at the strategy design pattern.
The common way of getting something like Javascript's closures is using anonymous inner classes. It's a lot more verbose, but it lets you do pretty much the same thing.
Runnable r = new Runnable(){
public void run(){
System.out.println("Hello, world!");
}
};
r.run(); // Prints "Hello, world!"
You can even reference variables in the enclosing method, if they're final:
public static Runnable makeGreeter(final String who) {
return new Runnable() {
public void run() {
System.out.println("Hello, " + who + "!");
}
};
}
// ... elsewhere in your program...
Runnable r = makeGreeter("world");
r.run(); // "Hello, world!"
This is standard stuff which has been in Java since the beginning. Runnable is a very handy interface which, according to the Javadocs, "should be implemented by any class whose instances are intended to be executed by a thread". Runnable can be used for a lot more than threads, of course, and is generally used (in the JVM and elsewhere) as "something that can be executed" - pretty much like a function in Javascript. Of course, if you want to pass arguments, you'd have to make your own interface, but those can be implemented anonymously as well. For example, using #Imagist's Function interface:
interface Function {
Object call(Object[] arguments);
}
// ...
Function helloSayer = new Function(){
public Object call(Object[] args){
System.out.println("Hello, " + args[0] + "!");
}
};
helloSayer.call(new Object[]{ "world" }); // "Hello, world!"
Edit: This has nothing to do with reflection, of course, but there's no reflection in your example either - just an anonymous function.
Are you after the dynamic creation of methods or Reflection?
The first you can't do in Java but you could use an interpreter (BeanShell if you want Java).
There are at least a few ways:
You could create classes at runtime with BCEL, but you have to create the bytecodes yourself. And the JVM's verifier might reject your class if your bytecodes look iffy. Not a super easy solution but doable.
Sun's Java 6 implementation includes Rhino, the JavaScript interpreter, so you can perhaps do what you need if you're willing to use a little JavaScript.
I'm not too sure about this but I believe if you have the JDK installed, you can invoke javac from your Java program. javac's output could be loaded at runtime with a custom ClassLoader class.
Does the Java language have delegate features, similar to how C# has support for delegates?
Not really, no.
You may be able to achieve the same effect by using reflection to get Method objects you can then invoke, and the other way is to create an interface with a single 'invoke' or 'execute' method, and then instantiate them to call the method your interested in (i.e. using an anonymous inner class).
You might also find this article interesting / useful : A Java Programmer Looks at C# Delegates (#blueskyprojects.com)
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:
// C#
public delegate void SomeFunction();
declare an interface:
// Java
public interface ISomeBehaviour {
void SomeFunction();
}
For concrete implementations of the method, define a class that implements the behaviour:
// Java
public class TypeABehaviour implements ISomeBehaviour {
public void SomeFunction() {
// TypeA behaviour
}
}
public class TypeBBehaviour implements ISomeBehaviour {
public void SomeFunction() {
// TypeB behaviour
}
}
Then wherever you would have had a SomeFunction delegate in C#, use an ISomeBehaviour reference instead:
// C#
SomeFunction doSomething = SomeMethod;
doSomething();
doSomething = SomeOtherMethod;
doSomething();
// Java
ISomeBehaviour someBehaviour = new TypeABehaviour();
someBehaviour.SomeFunction();
someBehaviour = new TypeBBehaviour();
someBehaviour.SomeFunction();
With anonymous inner classes, you can even avoid declaring separate named classes and almost treat them like real delegate functions.
// Java
public void SomeMethod(ISomeBehaviour pSomeBehaviour) {
...
}
...
SomeMethod(new ISomeBehaviour() {
#Override
public void SomeFunction() {
// your implementation
}
});
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:
// Java 8
SomeMethod(() -> { /* your implementation */ });
Short story: no.
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.
Have you read this :
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.
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
No, but they're fakeable using proxies and reflection:
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?"));
}
The nice thing about this idiom is that you can verify that the delegated-to method exists, and has the required signature, at the point where you create the delegator (although not at compile-time, unfortunately, although a FindBugs plug-in might help here), then use it safely to delegate to various instances.
See the karg code on github for more tests and implementation.
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.
I have implemented callback/delegate support in Java using reflection. Details and working source are available on my website.
How It Works
There is a principle class named Callback with a nested class named WithParms. The API which needs the callback will take a Callback object as a parameter and, if neccessary, create a Callback.WithParms as a method variable. Since a great many of the applications of this object will be recursive, this works very cleanly.
With performance still a high priority to me, I didn't want to be required to create a throwaway object array to hold the parameters for every invocation - after all in a large data structure there could be thousands of elements, and in a message processing scenario we could end up processing thousands of data structures a second.
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.
The WithParms nested class, then, is optional and serves two purposes, it contains the parameter object array needed for the callback invocations, and it provides 10 overloaded invoke() methods (with from 1 to 10 parameters) which load the parameter array and then invoke the callback target.
What follows is an example using a callback to process the files in a directory tree. This is an initial validation pass which just counts the files to process and ensure none exceed a predetermined maximum size. In this case we just create the callback inline with the API invocation. However, we reflect the target method out as a static value so that the reflection is not done every time.
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.
Defining and implementing an interface is not really so bad (unless you're distributing applets, as I am, where avoiding creating extra classes actually matters), but where this really shines is when you have multiple callbacks in a single class. Not only is being forced to push them each into a separate inner class added overhead in the deployed application, but it's downright tedious to program and all that boiler-plate code is really just "noise".
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:
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();
}
Every new object of type SingleFunc must implement printMe(), so it is safe to pass it to another method (e.g. delegate(SingleFunc)) to call the printMe() method.
With safety-mirror on the classpath you get something similar to C#'s delegates and events.
Examples from the project's README:
Delegates in 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"
Events
//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)
See also this SO answer.
While it is nowhere nearly as clean, but you could implement something like C# delegates using a Java Proxy.
No, but it has similar behavior, internally.
In C# delegates are used to creates a separate entry point and they work much like a function pointer.
In java there is no thing as function pointer (on a upper look) but internally Java needs to do the same thing in order to achieve these objectives.
For example, creating threads in Java requires a class extending Thread or implementing Runnable, because a class object variable can be used a memory location pointer.
No, Java doesn't have that amazing feature. But you could create it manually using the observer pattern. Here is an example:
Write C# delegate in java
The code described offers many of the advantages of C# delegates. Methods, either static or dynamic, can be treated in a uniform manner. The complexity in calling methods through reflection is reduced and the code is reusable, in the sense of requiring no additional classes in the user code. Note we are calling an alternate convenience version of invoke, where a method with one parameter can be called without creating an object array.Java code below:
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 doesn't have delegates and is proud of it :). From what I read here I found in essence 2 ways to fake delegates:
1. reflection;
2. inner class
Reflections are slooooow! Inner class does not cover the simplest use-case: sort function. Do not want to go into details, but the solution with inner class basically is to create a wrapper class for an array of integers to be sorted in ascending order and an class for an array of integers to be sorted in descending order.