Home

Advertisement

Java.has("duck typing"); //yet, too verbose

  • May. 21st, 2009 at 8:52 PM

I'm sure I'm not the first to blog this but let's go: This simple example shows how we can have the Duck Typing effect using reflection on the Java platform:

1:import static java.lang.System.out;
2:
3:public class VerboseButStillDuckTyping
4:{
5:    public static void main(String[] args) throws Exception
6:    {
7:        quack(new WoodDuck());
8:        quack(new Object());
9:    }
10:
11:    static void quack(Object obj) throws Exception
12:    {
13:        Duck.class.getMethod("quack", null).invoke(obj, null);
14:    }
15:}
16:
17:interface Duck { void quack(); }
18:
19:class WoodDuck implements Duck
20:{
21:    public void quack() { out.println("Quaaack!"); }
22:}

Above we are invoking the quack method on two references, one that has the needed implementation and the other which does not have. As expected the second invocation raises an runtime error, as with any dynamic language :-)

Of course this is just a proof of the concept and not what should be a regular practice on development with the Java language. This is just to remember that people very often does not proper recognize the dynamic features of the Java runtime environment.



Comment Form

From:
(will be screened)
Help(will be screened)
Identity URL: 
(will be screened)
Username:
Password:
Don't have an account? Create one now.
Subject:
No HTML allowed in subject
   Help
Message:
 
Notice! This user has turned on the option that logs your IP address when posting. Help

Latest Month

November 2009
S M T W T F S
1234567
891011121314
15161718192021
22232425262728
2930     

Tags

Powered by LiveJournal.com
Designed by Tiffany Chow