Skip to content

Commit

Permalink
Enable assigning a Number to java.lang.Character
Browse files Browse the repository at this point in the history
Use coerceToNumber when JS Type is numeric and target type is java.lang.Character. This lets you assign a JavaScript number to a java.lang.Character without triggering an exception.
  • Loading branch information
focJSi authored Feb 16, 2025
1 parent 11232bc commit 4d2c738
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -534,7 +534,8 @@ static Object coerceTypeImpl(Class<?> type, Object value) {
return coerceToNumber(
jsTypeCode == JSTYPE_BIGINT ? BigInteger.class : Double.TYPE, value);
} else if ((type.isPrimitive() && type != Boolean.TYPE)
|| ScriptRuntime.NumberClass.isAssignableFrom(type)) {
|| ScriptRuntime.NumberClass.isAssignableFrom(type)
|| ScriptRuntime.CharacterClass.isAssignableFrom(type)) {
return coerceToNumber(type, value);
} else {
reportConversionError(value, type);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
package org.mozilla.javascript.tests;

import static org.junit.jupiter.api.Assertions.assertEquals;

import org.junit.Test;
import org.mozilla.javascript.tools.shell.Global;

/**
* @author Jakob Silbereisen, Foconis Analytics GmbH
*/
public class CharacterAssignmentTest {

public static class X {
public Character bigCharacter;
public char primitiveCharacter;

public X() {}

public X(char c) {
bigCharacter = c;
primitiveCharacter = c;
}
}

@Test
public void assignCharacterTypesFromNumbers() {
Utils.runWithAllModes(
cx -> {
final Global scope = new Global();
scope.init(cx);
X x1 = new X(), x2 = new X();
scope.put("x1", scope, x1);
scope.put("x2", scope, x2);
scope.put("src", scope, new X('X'));
Object ret =
cx.evaluateString(
scope,
"x1.bigCharacter = 65;"
+ "x1.primitiveCharacter = 65;"
+ "x2.bigCharacter = src.primitiveCharacter;",
"myScript.js",
1,
null);
assertEquals('A', x1.bigCharacter);
assertEquals('A', x1.primitiveCharacter);
assertEquals('X', x2.bigCharacter);
return null;
});
}
}

0 comments on commit 4d2c738

Please sign in to comment.