dinamic classloader?

N

Novello

Hello,

My program needs to create a class, see code below to understand ;-)

/**
* Loads system's class and execute it
*/
private static void loadSystem(String systemName,String symbol) {

// wrong code:
systemName system = new systemName(symbol);

}

the first param is systemName, the name of the class to create.
I cannot create it such as "systemName system = new sytemName(symbol)"
because systemName is a String and not a Class.

How can I solve this problem?

If something is not clear please ask, I will explain better :)

thank you
 
C

Chris Smith

Novello said:
/**
* Loads system's class and execute it
*/
private static void loadSystem(String systemName,String symbol) {

// wrong code:
systemName system = new systemName(symbol);

}

the first param is systemName, the name of the class to create.
I cannot create it such as "systemName system = new sytemName(symbol)"
because systemName is a String and not a Class.

Google for "reflection". The basic pattern looks like this:

private static void loadSystem(String systemName,String symbol)
throws ...
{
Class c = Class.forName(systemName);
Constructor ctor = c.getConstructor(String.class);
Object system = ctor.newInstance(symbol);
}

(* This is 1.5 code. In 1.4 and previous versions, you'll need to
explicitly instantiate the Class[] in the getConstructor call, and the
Object[] in the newInstance call. 1.5 makes this cleaner. See the API
docs for the appropriate signatures for all of those methods.)

(** I've left out exception handling. When using reflection, there are
a gazillion things that might go wrong, so you should handle the
exceptions.)

Note that the reference you get back is of type Object, not of the
specific class you loaded. That's actually the best you can do; the
compiler obviously doesn't know what methods or fields are available for
that dynamic class. To use the object, you will need to do one of two
things: cast the object to an interface or superclass type that declares
the operations you need, or use reflection again to find the methods and
fields and to access them.

--
www.designacourse.com
The Easiest Way To Train Anyone... Anywhere.

Chris Smith - Lead Software Developer/Technical Trainer
MindIQ Corporation
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,754
Messages
2,569,521
Members
44,995
Latest member
PinupduzSap

Latest Threads

Top