| 1 | /* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- |
| 2 | * |
| 3 | * This Source Code Form is subject to the terms of the Mozilla Public |
| 4 | * License, v. 2.0. If a copy of the MPL was not distributed with this |
| 5 | * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ |
| 6 | |
| 7 | import org.mozilla.javascript.*; |
| 8 | |
| 9 | /** |
| 10 | * An example WrapFactory that can be used to avoid wrapping of Java types |
| 11 | * that can be converted to ECMA primitive values. |
| 12 | * So java.lang.String is mapped to ECMA string, all java.lang.Numbers are |
| 13 | * mapped to ECMA numbers, and java.lang.Booleans are mapped to ECMA booleans |
| 14 | * instead of being wrapped as objects. Additionally java.lang.Character is |
| 15 | * converted to ECMA string with length 1. |
| 16 | * Other types have the default behavior. |
| 17 | * <p> |
| 18 | * Note that calling "new java.lang.String('foo')" in JavaScript with this |
| 19 | * wrap factory enabled will still produce a wrapped Java object since the |
| 20 | * WrapFactory.wrapNewObject method is not overridden. |
| 21 | * <p> |
| 22 | * The PrimitiveWrapFactory is enabled on a Context by calling setWrapFactory |
| 23 | * on that context. |
| 24 | */ |
| 25 | public class PrimitiveWrapFactory extends WrapFactory { |
| 26 | @Override |
| 27 | public Object wrap(Context cx, Scriptable scope, Object obj, |
| 28 | Class<?> staticType) |
| 29 | { |
| 30 | if (obj instanceof String || obj instanceof Number || |
| 31 | obj instanceof Boolean) |
| 32 | { |
| 33 | return obj; |
| 34 | } else if (obj instanceof Character) { |
| 35 | char[] a = { ((Character)obj).charValue() }; |
| 36 | return new String(a); |
| 37 | } |
| 38 | return super.wrap(cx, scope, obj, staticType); |
| 39 | } |
| 40 | } |