Posted by Benjamin Johnston on 2000-04-10
Whoops... I forgot to change the subject. :) Subject: Re: TCG digest 731 > I would like to load a java class at runtime. However this class will be > special in that it will be a plugin for my application. Is there an example > somewhere that demonstrates how to load a java class at runtime and be able > to use its methods and things? Ok, If you know that the class will be in the classpath at runtime, then you can use java reflection to load it, get its methods and invoke it, without needing the class at design-time. eg. "Load" a class: Class loadedClass = Class.forName("Myclass"); Find a method of that class: java.lang.reflect.Method m = loadedClass.getMethod("init",null); (the second argument is a class array, representing the types of its arguments) Invoke that method: m.invoke(null, null); (the first argument is the object (if its not a static method) and the second argument is an object array containing the methods parameters). IF that class is not in the classpath, then you'll have to write your own classloader (ie. extend java.lang.ClassLoader). Note: When you're using reflection, the "Class" or type of an argument should be something like: Iterator.class <-for objects Object.class <-for objects Character.TYPE <-for primitive type Byte.TYPE <-for primitive types Object.class <-for arrays byte.class <-for primitive arrays I just noticed that byte.class seems to work too. And then when you're passing the arguments, its an object array containing the arguments themself, except that when you need to pass primitive types, you have to "wrap" them in their "wrapper-types" (eg. new Integer(5)) Look at the documentation for java.lang.Class, java.lang.reflect.* and java.lang.ClassLoader for more information. -Benjamin Johnston firstname.lastname@example.org To signoff send a mail to email@example.com with "signoff tcg" in the body of your message.
Previous post | Next post | Timeline | Home