Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to invoke a private constructor via reflection?

When I select a private constructor from the class members and try to instantiate an object a java.lang.NoSuchMethod exception is thrown.

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) ...

I expected to find methods that allow me to flag the private constructor as accessible but I could not find any.

like image 697
Taig Avatar asked Mar 25 '26 05:03

Taig


1 Answers

This seems to be a bug.

The other member lookups use getDeclaredXXX, and it's clear from the before and after of this commit of ConstructorMirror that it was always intended to setAccessible.

like image 122
som-snytt Avatar answered Mar 26 '26 20:03

som-snytt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!