 |
AppletTalk.com Java discussions newsgroups
|
| View previous topic :: View next topic |
| Author |
Message |
blaw@mkisserve.com Guest
|
Posted: Sat May 21, 2005 7:59 am Post subject: Loading and running a class |
|
|
Using the documentation provided by SUN, I have written the following
program:
import java.lang.reflect.*;
class RunClass
{
public static void main(String args[])
{
try {
Class c = Class.forName("MyClass");
Object obj = c.newInstance();
Class[] parameterTypes = null;
Method getMethod = c.getMethod("getData",parameterTypes);
Method putMethod = c.getMethod("putData",parameterTypes);
getMethod.invoke(obj,parameterTypes);
putMethod.invoke(obj,parameterTypes);
}
catch(InstantiationException ie) { System.out.println(ie); }
catch(ClassNotFoundException ie) { System.out.println(ie); }
catch(IllegalAccessException ie) { System.out.println(ie); }
catch(NoSuchMethodException ie) { System.out.println(ie); }
catch(InvocationTargetException ie) { System.out.println(ie); }
}
}
In order to get the method invoke function to work, I had to change the
parameters. This may be because I'm using following version of java.
java -version
java version "1.4.2-rc1"
Java(TM) 2 Runtime Environment, Standard Edition (build
Blackdown-1.4.2-rc1)
Java HotSpot(TM) Client VM (build Blackdown-1.4.2-rc1, mixed mode)
My question is how to I call the method invoke routine and pass it
parameters and get a result back?
Any help is appreciated.
Thanks,
Bob Law
|
|
| Back to top |
|
 |
Janwillem Borleffs Guest
|
Posted: Sat May 21, 2005 9:58 am Post subject: Re: Loading and running a class |
|
|
[email]blaw (AT) mkisserve (DOT) com[/email] wrote:
| Quote: | My question is how to I call the method invoke routine and pass it
parameters and get a result back?
|
class MyClass {
public void printHello(String name) {
System.out.println("Hello " + name);
}
}
class RunClass {
public static void main(String args[]) {
try {
Class c = Class.forName("MyClass");
Object obj = c.newInstance();
Class[] parameters = { new String().getClass() };
Method printHello = c.getMethod("printHello", parameters);
Object[] input = { "Joe" };
printHello.invoke(obj, input);
} catch (Exception e) {
e.printStackTrace();
}
}
}
See also: http://www.angelfire.com/tx4/cus/shapes/covariance.html
HTH;
JW
|
|
| Back to top |
|
 |
|
|
You cannot post new topics in this forum You cannot reply to topics in this forum You cannot edit your posts in this forum You cannot delete your posts in this forum You cannot vote in polls in this forum
|
|