Class loader

N

Novello

Hello,

Imagine to have a menu on the left loaded dynamically, each item has its
own command to run.
In the rest of window I have a tabPane where I have to load the class I get
from menu.

Menu gives me the name of the class to load for example win01
I have to get the ContentPane of this class and load it inside a new
TabbedPane

I tried with forName but I canno tcast it to a JFrame to get the
contentPane.
I know that the class I have to load is always a JFrame class.

Any ideas?

thank you all!
 
N

Novello

Code

the following method of class Loader loads the class and return it but I
cannot cast it to a JFrame to get the content, see next code section to
understand.

any ideas?

public Class loadClass() throws Throwable {

className = MODULES_REPO + className.toLowerCase() + "." +
className;
Class[] cArgs = new Class[1];
cArgs[0] = String.class;

Class aClass = Class.forName(className);
Class[] argumentTypes = { java.lang.String.class };
Constructor oneArgument = null;
try {
oneArgument = aClass.getConstructor( argumentTypes );
} catch (SecurityException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (NoSuchMethodException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
Object[] arguments = { parm1 };
try {
oneArgument.newInstance( arguments );
} catch (IllegalArgumentException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
} catch (InstantiationException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
} catch (IllegalAccessException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
} catch (InvocationTargetException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
return aClass;
}



Here, where I call the Loader Class above

Loader loader = new Loader(mItem.getClassName());
JFrame l = (JFrame) loader.loadClass(); // cast does not work

mainTabPane.addTab(mItem.getItemName(),icon,l.getContentPane(),mItem.getItem
Name());

thank you!
 
A

Andrew Thompson

Loader loader = new Loader(mItem.getClassName());
JFrame l = (JFrame) loader.loadClass(); // cast does not work

'ClassLoader.loadClass()' returns byte[]s, not a class.

See the preamble of the JavaDocs for ClassLoader to see mention
of 'defineClass' which returns a Class of those bytes and..
Class.newInstance() for a 'no args' constructed object.

If you need one of the constructors that uses parameters,
you may need to use Class methods to retrieve an appropriate
Constructor and call newInstance() with your params.

HTH
 

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,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top