Re: delegates equivalent
From: Fritz (fritz_foetzl_at_hotmail.com)
Date: 01/31/05
- Next message: quickcur_at_yahoo.com: "Re: online store example"
- Previous message: GuyBrush Treepwood: "delegates equivalent"
- In reply to: GuyBrush Treepwood: "delegates equivalent"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
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"));
}
- Next message: quickcur_at_yahoo.com: "Re: online store example"
- Previous message: GuyBrush Treepwood: "delegates equivalent"
- In reply to: GuyBrush Treepwood: "delegates equivalent"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Relevant Pages
|