[Nashorn] (numExpr).getClass()

投稿日: 2015/12/05 15:06:14

小さな整数リテラルはjava.lang.Integerとみなされますが、計算式に使用するとjava.lang.Doubleに変換されます。java.math.BigDecimalも計算式に使用できますが、やはりjava.lang.Doubleに変換されます。

1. 実行するスクリプト(numExprGetClass.js)

function assertEq(f,x) {var r=f();if(r!==x)throw new Error(f.toSource()+", expected=${x}, actual=${r}");}
var Double = Java.type("java.lang.Double");
var Integer = Java.type("java.lang.Integer");
var BigDecimal = Java.type("java.math.BigDecimal");
assertEq(function() (100).getClass(), Integer.class);
assertEq(function() (100.0).getClass(), Double.class);
var intValue = 1;
try {
    assertEq(function() (intValue + 1).getClass(), Integer.class);
} catch(e) { print(e); }
try {
    assertEq(function() (100 + Integer.MIN_VALUE).getClass(), Integer.class);
} catch(e) { print(e); }
assertEq(function() (Integer.valueOf(200) * 2.5).getClass(), Double.class);
print("\nBigDecimal.TEN + 1 => " + (BigDecimal.TEN + 1));
try {
    assertEq(function() (BigDecimal.TEN + 1).getClass(), BigDecimal.class);
} catch(e) { print(e); }
print("\nBigDecimal.TEN + BigDecimal.ONE => " + (BigDecimal.TEN + BigDecimal.ONE));
try {
    assertEq(function() (BigDecimal.TEN + BigDecimal.ONE).getClass(), BigDecimal.class);
} catch(e) { print(e); }
assertEq(function() (BigDecimal.TEN.add(BigDecimal.ONE)).getClass(), BigDecimal.class);

2. jjsで実行する

>jjs -scripting -fullversion numExprGetClass.js
nashorn full version 1.8.0_66-b18
Error: function() (intValue + 1).getClass(), expected=class java.lang.Integer, actual=class java.lang.Double
Error: function() (100 + Integer.MIN_VALUE).getClass(), expected=class java.lang.Integer, actual=class java.lang.Double
BigDecimal.TEN + 1 => 11
Error: function() (BigDecimal.TEN + 1).getClass(), expected=class java.math.BigDecimal, actual=class java.lang.Double
BigDecimal.TEN + BigDecimal.ONE => 11
Error: function() (BigDecimal.TEN + BigDecimal.ONE).getClass(), expected=class java.math.BigDecimal, actual=class java.lang.Double