经过漫长的一天搜索,如果构造函数采用非原始参数,我仍然无法弄清楚如何从自制类中实现新对象.现在我开始怀疑这是否可行?!
在Reflection的文档中,就我所见,他们只讨论基本类型(如int,float,boolean等).我发现的所有其他信息/网站/研讨会/示例也只是考虑原始类型来查找构造函数并实例化一个新实例.
所以我想要做的是以下(细分场景):
假设我有一个名为MyStupidClass的类.另一个类(我们将其命名为MyUsingClass)将MyStupidClass对象作为构造函数中的参数.现在在我的主应用程序中,我希望能够加载MyUsingClass类并将构造函数中的对象实例化.
这是我到目前为止发现的"使用反射":
使用空构造函数:
//the MyUsingClass:
public class MyUsingClass {
//the public (empty) constructor
public MyUsingClass() {
...
}
}
Run Code Online (Sandbox Code Playgroud)
在主应用程序中,我现在会做类似的事情:
//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);
Run Code Online (Sandbox Code Playgroud)
现在如果我在MyUsingClass中使用一些原始类型,它看起来像:
//the MyUsingClass:
public class MyUsingClass { …Run Code Online (Sandbox Code Playgroud)