/** * Converts JavaScript object to Java object, e.g. HostedJavaObject into wrapped Java object. * * @param jsObj JavaScript object to be converted. * @return Converted Java object. */ public static Object jsToJava(Object jsObj) { if (jsObj instanceof Wrapper) { Wrapper njb = (Wrapper) jsObj; if (njb instanceof NativeJavaClass) { return njb; } Object obj = njb.unwrap(); if (obj instanceof Number || obj instanceof String || obj instanceof Boolean || obj instanceof Character) { return njb; } else { return obj; } } else { return jsObj; } }
/** * We convert script values to the nearest Java value. * We unwrap wrapped Java objects so that access from * Bindings.get() would return "workable" value for Java. * But, at the same time, we need to make few special cases * and hence the following function is used. */ private Object jsToJava(Object jsObj) { if (jsObj instanceof Wrapper) { Wrapper njb = (Wrapper) jsObj; /* importClass feature of ImporterTopLevel puts * NativeJavaClass in global scope. If we unwrap * it, importClass won't work. */ if (njb instanceof NativeJavaClass) { return njb; } /* script may use Java primitive wrapper type objects * (such as java.lang.Integer, java.lang.Boolean etc) * explicitly. If we unwrap, then these script objects * will become script primitive types. For example, * * var x = new java.lang.Double(3.0); print(typeof x); * * will print 'number'. We don't want that to happen. */ Object obj = njb.unwrap(); if (obj instanceof Number || obj instanceof String || obj instanceof Boolean || obj instanceof Character) { // special type wrapped -- we just leave it as is. return njb; } else { // return unwrapped object for any other object. return obj; } } else { // not-a-Java-wrapper return jsObj; } }