﻿ javascript-如何在jjs / Nashorn中使用java.math.BigInteger？ - 代码日志

#### javascript-如何在jjs / Nashorn中使用java.math.BigInteger？

``````public static BigInteger fibonacci(int n) {
BigInteger prev = new BigInteger("0");
if (n == 0) return prev;

BigInteger next = new BigInteger("1");
if (n == 1) return next;

BigInteger fib = null;
int i;
for (i = 1; i < n; i++) {
prev = next;
next = fib;
}
return fib;
}
``````

> n = 77：5527939700884757
> n = 78：8944394323791464
> n = 79：14472334024676221

``````function fibonacci(n) {
var BigInteger = Java.type("java.math.BigInteger");
prev = new BigInteger("0");
if (n == 0) return prev;

next = new BigInteger("1");
if (n == 1) return next;

var i, fib = null;
for (i = 1; i < n; i++) {
prev = next;
next = fib;
}
return fib;
}
``````

> n = 77：5527939700884757
> n = 78：8944394323791464
> n = 79：14472334024676220

``````var BigInteger = Java.type("java.math.BigInteger");
print(new BigInteger("14472334024676221"));
``````

``````var str, BigInteger = Java.type("java.math.BigInteger");
str = "9999999999999998";
print(str + ": " + new BigInteger(str));
str = "9999999999999999";
print(str + ": " + new BigInteger(str));
``````

> 9999999999999998：9999999999999998
> 9999999999999999：10000000000000000

JSType和其他几个地方都进行了“ instanceof Number”检查-不知道单独修复JSType.toStringImpl是否可以.无论如何,我都有一个解决方法-不是一个很漂亮的方法-但还是有一个解决方法.您可以在这些对象上调用java.lang.Object.toString方法,从而避免使用Nashorn的JSType字符串转换代码.

``````function fibonacci(n) {
var BigInteger = Java.type("java.math.BigInteger");
prev = new BigInteger("0");
if (n == 0) return prev;

next = new BigInteger("1");
if (n == 1) return next;

var i, fib = null;
for (i = 1; i < n; i++) {
prev = next;
next = fib;
}
return fib;
}

function javaToString(obj) {
var javaToStringMethod = (new java.lang.Object()).toString;
var call = Function.prototype.call;
return call.call(javaToStringMethod, obj);
}

print(javaToString(fibonacci(77)))
print(javaToString(fibonacci(78)))
print(javaToString(fibonacci(79)))

var str, BigInteger = Java.type("java.math.BigInteger");
str = "9999999999999998";
print(str + ": " + javaToString(new BigInteger(str)));
str = "9999999999999999";
print(str + ": " + javaToString(new BigInteger(str)));
``````