View Full Version : [JAVA] Caricare classi dinamicamente
Con il seguente codice riesco a caricare una classe
try {
Class c = Class.forName( "pakage.Classe" ) ;
Object o = c.newInstance() ;
} catch ( Exception e ) {
e.printStackTrace() ;
}
Ma ad esempio se volossi passare alla classe caricata anche uno o pių paramteri come posso fare?
Grazie ciao
Devi costruirti un metodo apposta... non so se nelle ultime versioni di Java č stato implementato un metodo che accetta parametri del costruttore... Io usavo questo:
protected Object newInstance(Object[] _params)
throws FactoryException
{
Object ret = null;
try
{
Class clInst = Class.forName(className);
Class[] params = new Class[_params.length];
Object[] objects = new Object[_params.length];
for(int i = 0; i < _params.length; i++)
{
params[i] = _params[i].getClass();
//System.out.println(i + " classe: " + _params[i].getClass().getName());
objects[i] = _params[i];
}
Constructor constructor = clInst.getConstructor(params);
//System.out.println("Constructor: " + constructor.getName());
//Object[] objects = new Object[]{_params};
ret = constructor.newInstance(objects);
}catch(ClassNotFoundException cnfe){
StringBuffer sb = new StringBuffer("ClassNotFoundException: ");
sb.append(cnfe.getMessage());
cnfe.printStackTrace(System.out);
throw new FactoryException(sb.toString());
}catch(NoSuchMethodException nsme){
StringBuffer sb = new StringBuffer("NoSuchMethodException: ");
sb.append(nsme.getMessage());
nsme.printStackTrace(System.err);
throw new FactoryException(sb.toString());
}catch(InvocationTargetException ite){
StringBuffer sb = new StringBuffer("InvocationTargetException: ");
sb.append(ite.getMessage());
ite.printStackTrace(System.out);
throw new FactoryException(sb.toString());
}catch(InstantiationException ie){
StringBuffer sb = new StringBuffer("InstantiationException: ");
sb.append(ie.getMessage());
ie.printStackTrace(System.out);
throw new FactoryException(sb.toString());
}catch(IllegalAccessException iae){
StringBuffer sb = new StringBuffer("IllegalAccessException: ");
sb.append(iae.getMessage());
iae.printStackTrace(System.out);
throw new FactoryException(sb.toString());
}
return ret;
}
:D :D
Fichissimo grazie... adesso lo provo poi ti so dire
vBulletin® v3.6.4, Copyright ©2000-2025, Jelsoft Enterprises Ltd.