What problems should I expect when using Reflection to interact with java.math.BigInteger?

I am implementing a faster implementation BigInt, and I'm not sure how far I have to go in order to interact with the underlying platform.

Today it BigIntjust wraps BigInteger, and the value BigIntegerjust returns the wrapped value:

class BigInt(val bigInteger: BigInteger) ...

Since I am not wrapping a Java type, I would need to do something like

final class BigInt private(final val signum: Int,
                           final private[math] val arr: Array[Int])
  def bigInteger: java.math.BigInteger = {
    // Avoid copying of potentially large arrays.
    val ctor = classOf[java.math.BigInteger]
                 .getDeclaredConstructor(classOf[Array[Int]], classOf[Int])
    ctor setAccessible true
    ctor.newInstance(arr, signum.asInstanceOf[Object])
  }
...
}

Could this cause problems or is there a better way to do this?

+5
source share
1 answer

, , ( ) , , NoSuchMethodException :

object BigInt {
  import java.math.BigInteger

  private val toBigInteger: (Array[Int], Int) => BigInteger = try {
    val ctor = classOf[BigInteger].getDeclaredConstructor(
      classOf[Array[Int]], classOf[Int]
    )
    ctor.setAccessible(true)

    (arr, signum) => ctor.newInstance(arr, signum.asInstanceOf[Object])
  } catch { case _: NoSuchMethodException =>
    (arr, signum) =>
      val buffer = java.nio.ByteBuffer.allocate(arr.length * 4)
      buffer.asIntBuffer.put(arr)
      new BigInteger(signum, buffer.array)
  }
}

final class BigInt(final val signum: Int, final val arr: Array[Int]) {
  def bigInteger = BigInt.toBigInteger(arr, signum)
}

-, , bigInteger.

+3

All Articles