After a long day of searching, I still cannot figure out how I can create a new object from a self-contained class if the constructor takes non-primitive arguments. Now I'm starting to doubt whether this is possible at all ?!
In the Documentation of Reflection, they only talk about primitive types (e.g. int, float, boolean, etc.) as far as I saw, And all other information / website / seminar / example I found also just look at primitive types to find the constructor and create a new instance.
So what I want to do is the following (broken script):
Suppose I have a class called MyStupidClass. Another class (let its name be MyUsingClass) takes a MyStupidClass object as an argument in the constructor. Now in my main application, I want to be able to load the MyUsingClass class and initialize the object from the constructor.
Here is what I learned about "using Reflection":
With an empty constructor:
public class MyUsingClass {
public MyUsingClass() {
...
}
}
In the main application, I would now do something like:
Class<?> myUsingClassClass = Class.forName("MyUsingClass");
Constructor<?> myUsingClassConstr = myUsingClassClass.getConstructor();
Object myInstance = myUsingClassConstr.newInstance(null);
Now, if I were to use some primitive types in MyUsingClass , it would look something like this:
public class MyUsingClass {
public MyUsingClass(String a, int b) {
...
}
}
In the main application, the last line will change to something like:
Object myInstance = myUsingClassConstr.newInstance(new Object[]{new String("abc"), new Integer(5)});
( , ...)
, myInstance, MyUsingClass :
public class MyUsingClass {
public MyUsingClass(String a, int b, MyStupidObject toto) {
...
}
}
? ! , !
sv