当我从类成员中选择一个私有构造函数并尝试实例化一个对象时,java.lang.NoSuchMethod
会引发异常。
scala> import scala.reflect.runtime.universe._
import scala.reflect.runtime.universe._
scala> class test private( s: String ) {
| def this( i: Int ) = this( i.toString ) // public
| }
defined class test
scala> val mirror = runtimeMirror( getClass.getClassLoader )
mirror: reflect.runtime.universe.Mirror = JavaMirror with scala.tools.ns...
scala> val cls = mirror.classSymbol( classOf[test] )
cls: reflect.runtime.universe.ClassSymbol = class test
scala> cls.toType.members.toSeq
res0: reflect.runtime.universe.MemberScope = Scopes(constructor test, constructor test, value s, meth...
scala> val prv = res0( 1 ).asMethod
prv: reflect.runtime.universe.MethodSymbol = constructor test
scala> val pub = res0( 0 ).asMethod
pub: reflect.runtime.universe.MethodSymbol = constructor test
scala> mirror.reflectClass( cls ).reflectConstructor( pub ).apply( 1 )
res3: Any = test@6926e27
scala> mirror.reflectClass( cls ).reflectConstructor( prv ).apply( "1" )
java.lang.NoSuchMethodException: test.<init>(java.lang.String) ...
我希望找到允许我将私有构造函数标记为可访问的方法,但我找不到任何方法。