1. Why does this code go bust?
2. Do you have a working example of invoking an object by reflection (Object.invoke), which is quoted on Pg. 235 of my book., but somehow I can't find it documented within the [url=http://www.amazon.com/Core-Java-TM-I-Fundamentals-8th/dp/0132354764]API.[url]
Error message Microsoft Windows XP [Version 5.1.2600]
(C) Copyright 1985-2001 Microsoft Corp.
javac -Xlint Run
RunMthdRef.java:29: warning: [unchecked] unchecked call to getMethod(java.lang.S
tring,java.lang.Class<?>...) as a member of the raw type java.lang.Class Method mthd=cl.getMethod("add",par);
RunMthdRef.java:30: warning: non-varargs call of varargs method with inexact arg
ument type for last parameter;
cast to java.lang.Object for a varargs call
cast to java.lang.Object for a non-varargs call and to suppress this warning
Integer output=(Integer)mthd.invoke(new RunMthdRef(),input);
Jon, those weren't errors but warnings. The first one because java.lang.Class is generic; adding the <?> as Emmanuel did will solve that. The second one is because Method.invoke uses varargs, and the Integer is both an Object and an Object. It's treated as the latter though.
Emmanuel's code will already get rid of the warnings, but the entire Integer is not necessary:
This is bad use of reflection by the way; you already have access to the runMthdRef class at compile time, as you're using it on line 5. I can achieve the exact same with one line of code:
Reflection should be used if:
- a class itself or its name is not known at compile time but only at runtime
- a method to call itself or its name is not known at compile time but only at runtime
- a field to use itself or its name is not known at compile time but only at runtime
Well, when something or its name is not known at compile time but only at runtime. In your example, if the RunMthdRef class would not be known at compile time or the class name could come from a configuration file or something, the following would be proper use of reflection:
Although usually you would use an interface instead. For instance, to use any type of List:
If the argument to this application is java.util.LinkedList a LinkedList will be used, if it's java.util.ArrayList an ArrayList will be used. No matter the class, it's still a List so you can use it as such, including calling its methods.