[英]Creating class with parameter constructor in Scala reflection
我有一個可能需要 1 到 4 個參數的類。 它們總是字符串。 我想根據傳遞給函數的參數數量創建此類的對象。 有沒有辦法繞過必須創建構造函數並將對象數組直接傳遞給 newInstance 的方法?
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 解釋器中的這段代碼似乎不起作用。 任何幫助表示贊賞。
你弄錯了(更不用說,它是java語法,而不是scala)。 像這樣的東西應該在 Scala 中工作:
classOf[NewInstanceWithReflection]
.getDeclaredConstructor(classOf[String])
.newInstance("StackOverFlow")
這就是你在 Java 中所需要的:
NewInstanceWithReflection
.class
.getDeclaredConstructor(String.class)
.newInstance("StackOverFlow")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.