2016-04-26 192 views
0

我有一个类可能需要1到4个参数。他们总是字符串。我想根据传递给函数的参数数量来创建这个类的一个对象。有没有什么办法可以创建构造函数并将对象数组直接传递给newInstance?在Scala反射中创建带参数构造函数的类

 NewInstanceWithReflection clazz = (NewInstanceWithReflection)Class.forName("NewInstanceWithReflection").newInstance(); 
     Constructor constructor = NewInstanceWithReflection.class.getDeclaredConstructor(new Class[] {String.class}); 
     NewInstanceWithReflection object1 = (NewInstanceWithReflection)clazz.newInstance(new Object[]{"StackOverFlow"}); 

此代码粘贴到sbt解释器似乎并不工作。任何帮助赞赏。

回答

0

你明白了(更不用说,它是java的语法,而不是scala)。 像这样的东西应该在斯卡拉工作:

classOf[NewInstanceWithReflection] 
    .getDeclaredConstructor(classOf[String]) 
    .newInstance("StackOverFlow") 

这就是你需要在Java什么:

NewInstanceWithReflection 
    .class 
    .getDeclaredConstructor(String.class) 
    .newInstance("StackOverFlow") 
+0

对不起,我搞砸了我的代码示例。我只想知道是否可以跳过'.getDeclaredConstructor(classOf [String])',因为String args的数量可能会从1到4变化,只是将动态数量的args传递给'newInstance'方法。 – NNamed

+0

不,这是不可能的......'newInstance'是'Constructor'对象上的一个方法。你需要拥有这个对象才能调用它的一个方法。所以,“跳过”获取对象实例是行不通的。 – Dima

相关问题