Re: delegates equivalent

From: Fritz (fritz_foetzl_at_hotmail.com)
Date: 01/31/05


Date: 30 Jan 2005 20:31:33 -0800


GuyBrush Treepwood wrote:
> Whta is the simplest way to have something like multicast delegates
from
> C# in Java.
> And I mean really simple, no events and stuff.
> A Java interpretation for :
>
> public delegate void OutputDelegate(string input);
>
> class DisplayClass{
>
> public void display(string input){
> Console.WriteLine("method 'display' gets as input: {0}",
input);
> }
> }
>
> class PrintClass{
>
> public void print(string input){
> Console.WriteLine("method 'print' gets as input: {0}", input);
> }
> }
>
> class MainClass{
> static void Main(string[] args)
> DisplayClass display = new DisplayClass();
> PrintClass print = new PrintClass();
>
> OutputDelegate del = new OutputDelegate(display.display);
> del += print.print;
> del("test");
> }
> }

Should be something like this, where DisplayClass and PrintClass are
Java versions of your classes above. It's not as tidy as the C#
approach; delegates are one of the things I like better about C# than
Java. Maybe if someone else weighs in, they can come up with a cleaner
approach. Anyway...

java.lang.reflect.*;

public static void main (String[] args) {
DisplayClass display = new DisplayClass();
PrintClass print = new PrintClass();
Class dc = Class.forName ("DisplayClass");
Class pc = Class.forName ("PrintClass");
Method[] methods = new Method[2];
Class[] arg = new Class[1];

arg[0] = new String();
method[0] = dc.getDeclaredMethod("display", arg);
method[1] = pc.getDeclaredMethod("print", arg);

method[0].invoke (display, new String("test"));
method[1].invoke (print, new String("test"));
}



Relevant Pages

  • Re: Is Ruby On Rails, Delphis lost cousing?
    ... The closest analogue in Java is anonymous classes, ... Delegates as a first-class ... language feature alone makes me happier using it. ... Java Mustang does have some of this same functionality. ...
    (borland.public.delphi.non-technical)
  • Re: Delegates...?
    ... get round the fact that Java does not have delegates. ... presenter class which binds the two together. ... one uses inner classes in ...
    (comp.lang.java.programmer)
  • Re: Delegates...?
    ... Buried in that article is actually an example of how a behavior similar to delegates in C# can be implemented in Java. ... I see you have posted a good example of the human capacity for dismissing someone's point without having to provide a rationale. ... Simply labeling the article "a good example of the human capacity for rationalization" doesn't invalidate anything the article has to say. ...
    (comp.lang.java.programmer)
  • motivation behind delegates
    ... confused as to the motivation behind delegates. ... exactly like using interfaces in java, so why have another construct to ... confuse things? ... I know they work "like function pointers" but the whole reason I went to ...
    (microsoft.public.dotnet.framework)