After a long day of searching, I still can't figure out how I can instanciate a new object from a selfmade class, if the constructor takes non-primitive arguments. Now I start doubting if this is possible at all?!
In the Documentation of Reflection, they only talk about primitive types (like int, float, boolean, etc.) as far as I saw. And all other information/website/workshop/example I found also just consider primitive types to find the constructor and instanciate a new instance.
So what I want to do is the following (broken down scenario):
Suppose I got a class called MyStupidClass. Another class (let's name it MyUsingClass) takes a MyStupidClass object as argument in the constructor. Now in my main application, I want to be able to load the MyUsingClass class and instanciate an object out of the constructor.
This is what I found out about "using Reflection" so far:
With empty constructor:
//the MyUsingClass:
public class MyUsingClass {
//the public (empty) constructor
public MyUsingClass() {
...
}
}
In the main application, I would now do something like:
//get the reflection of the MyUsingClass
Class<?> myUsingClassClass = Class.forName("MyUsingClass");
//get the constructor [I use getConstructor() instead of getConstructors(...) here as I know there is only one]
Constructor<?> myUsingClassConstr = myUsingClassClass.getConstructor();
//instanciate the object through the constructor
Object myInstance = myUsingClassConstr.newInstance(null);
Now if I would use some primitive types in MyUsingClass, it would look something like:
//the MyUsingClass:
public class MyUsingClass {
//the public (primitive-only) constructor
public MyUsingClass(String a, int b) {
...
}
}
In the main application, the last line would change to something like:
//instanciate the object through the constructor
Object myInstance = myUsingClassConstr.newInstance(new Object[]{new String("abc"), new Integer(5)});
So far no problems (there might be some small errors in the code above as it is only a broken down example...) Now the clue question is, how can I create myInstance, if the MyUsingClass looks something like:
//the MyUsingClass:
public class MyUsingClass {
//the public (primitive-only) constructor
public MyUsingClass(String a, int b, MyStupidObject toto) {
...
}
}
? Any help would be appreciated! Thank you already for reading through my question!
greets sv
Stringis not a primitive. Did you try to do the same forMyStupidObjectas you did forString?