PDA

View Full Version : [Java] Reflection


ally
02-07-2010, 11:16
...ciao...

...sto smanacciando un po' con la reflection...


public static void main(String[] args) {

createObject("it.ally.Test");
}

static Object createObject(String className) {
Object object = null;
try {
Class classDefinition = Class.forName(className);
classDefinition.newInstance();
} catch (Exception e) {
System.out.println(e);
}
return object;
}



public class Test {

public Test(){

System.out.println("reflection!");

}

public Test(String arguments){

System.out.println(arguments);

}

}


...come è possibile passare argomenti nel momento di istanziare la classe?

...ciao Andrea...

ally
02-07-2010, 11:59
...dopo un po' di strani smanacciamenti :


public static void main(String[] args) {

Class reflectionClass;
Class[] intArgsClass = new Class[] {String.class};
String string = "ciao";
Object[] intArgs = new Object[] {string};
Constructor intArgsConstructor;

try {
reflectionClass = Class.forName("it.ally.Test");
intArgsConstructor = reflectionClass.getConstructor(intArgsClass);
createObject(intArgsConstructor, intArgs);
} catch (ClassNotFoundException e) {
System.out.println(e);
} catch (NoSuchMethodException e) {
System.out.println(e);
}
}

public static Object createObject(Constructor constructor,
Object[] arguments) {

System.out.println ("Constructor: " + constructor.toString());
Object object = null;

try {
object = constructor.newInstance(arguments);
System.out.println ("Object: " + object.toString());
return object;
} catch (Exception e) {
System.out.println(e);
}
return object;
}

ally
02-07-2010, 12:07
...la mia idea sarebbe di implementare la reflection per un sistema multi thread...avete idee o opinioni sull'uso migliore della reflection?...

...ciao Andrea...