NativeJava.java revision 1060:ca67ae7c46cb
1/* 2 * Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved. 3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 4 * 5 * This code is free software; you can redistribute it and/or modify it 6 * under the terms of the GNU General Public License version 2 only, as 7 * published by the Free Software Foundation. Oracle designates this 8 * particular file as subject to the "Classpath" exception as provided 9 * by Oracle in the LICENSE file that accompanied this code. 10 * 11 * This code is distributed in the hope that it will be useful, but WITHOUT 12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 14 * version 2 for more details (a copy is included in the LICENSE file that 15 * accompanied this code). 16 * 17 * You should have received a copy of the GNU General Public License version 18 * 2 along with this work; if not, write to the Free Software Foundation, 19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 20 * 21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 22 * or visit www.oracle.com if you need additional information or have any 23 * questions. 24 */ 25 26package jdk.nashorn.internal.objects; 27 28import static jdk.nashorn.internal.runtime.ECMAErrors.typeError; 29import static jdk.nashorn.internal.runtime.ScriptRuntime.UNDEFINED; 30import java.lang.invoke.MethodHandles; 31import java.lang.reflect.Array; 32import java.util.Collection; 33import java.util.Deque; 34import java.util.List; 35import jdk.internal.dynalink.beans.StaticClass; 36import jdk.internal.dynalink.support.TypeUtilities; 37import jdk.nashorn.api.scripting.JSObject; 38import jdk.nashorn.internal.objects.annotations.Attribute; 39import jdk.nashorn.internal.objects.annotations.Function; 40import jdk.nashorn.internal.objects.annotations.ScriptClass; 41import jdk.nashorn.internal.objects.annotations.Where; 42import jdk.nashorn.internal.runtime.Context; 43import jdk.nashorn.internal.runtime.JSType; 44import jdk.nashorn.internal.runtime.ListAdapter; 45import jdk.nashorn.internal.runtime.PropertyMap; 46import jdk.nashorn.internal.runtime.ScriptFunction; 47import jdk.nashorn.internal.runtime.ScriptObject; 48import jdk.nashorn.internal.runtime.ScriptRuntime; 49import jdk.nashorn.internal.runtime.linker.Bootstrap; 50import jdk.nashorn.internal.runtime.linker.JavaAdapterFactory; 51 52/** 53 * This class is the implementation for the {@code Java} global object exposed to programs running under Nashorn. This 54 * object acts as the API entry point to Java platform specific functionality, dealing with creating new instances of 55 * Java classes, subclassing Java classes, implementing Java interfaces, converting between Java arrays and ECMAScript 56 * arrays, and so forth. 57 */ 58@ScriptClass("Java") 59public final class NativeJava { 60 61 // initialized by nasgen 62 @SuppressWarnings("unused") 63 private static PropertyMap $nasgenmap$; 64 65 private NativeJava() { 66 // don't create me 67 throw new UnsupportedOperationException(); 68 } 69 70 /** 71 * Returns true if the specified object is a Java type object, that is an instance of {@link StaticClass}. 72 * @param self not used 73 * @param type the object that is checked if it is a type object or not 74 * @return tells whether given object is a Java type object or not. 75 * @see #type(Object, Object) 76 */ 77 @Function(attributes = Attribute.NOT_ENUMERABLE, where = Where.CONSTRUCTOR) 78 public static boolean isType(final Object self, final Object type) { 79 return type instanceof StaticClass; 80 } 81 82 /** 83 * Returns synchronized wrapper version of the given ECMAScript function. 84 * @param self not used 85 * @param func the ECMAScript function whose synchronized version is returned. 86 * @param obj the object (i.e, lock) on which the function synchronizes. 87 * @return synchronized wrapper version of the given ECMAScript function. 88 */ 89 @Function(name="synchronized", attributes = Attribute.NOT_ENUMERABLE, where = Where.CONSTRUCTOR) 90 public static Object synchronizedFunc(final Object self, final Object func, final Object obj) { 91 if (func instanceof ScriptFunction) { 92 return ((ScriptFunction)func).makeSynchronizedFunction(obj); 93 } 94 95 throw typeError("not.a.function", ScriptRuntime.safeToString(func)); 96 } 97 98 /** 99 * Returns true if the specified object is a Java method. 100 * @param self not used 101 * @param obj the object that is checked if it is a Java method object or not 102 * @return tells whether given object is a Java method object or not. 103 */ 104 @Function(attributes = Attribute.NOT_ENUMERABLE, where = Where.CONSTRUCTOR) 105 public static boolean isJavaMethod(final Object self, final Object obj) { 106 return Bootstrap.isDynamicMethod(obj); 107 } 108 109 /** 110 * Returns true if the specified object is a java function (but not script function) 111 * @param self not used 112 * @param obj the object that is checked if it is a Java function or not 113 * @return tells whether given object is a Java function or not 114 */ 115 @Function(attributes = Attribute.NOT_ENUMERABLE, where = Where.CONSTRUCTOR) 116 public static boolean isJavaFunction(final Object self, final Object obj) { 117 return Bootstrap.isCallable(obj) && !(obj instanceof ScriptFunction); 118 } 119 120 /** 121 * Returns true if the specified object is a Java object but not a script object 122 * @param self not used 123 * @param obj the object that is checked 124 * @return tells whether given object is a Java object but not a script object 125 */ 126 @Function(attributes = Attribute.NOT_ENUMERABLE, where = Where.CONSTRUCTOR) 127 public static boolean isJavaObject(final Object self, final Object obj) { 128 return obj != null && !(obj instanceof ScriptObject); 129 } 130 131 /** 132 * Returns true if the specified object is a ECMAScript object, that is an instance of {@link ScriptObject}. 133 * @param self not used 134 * @param obj the object that is checked if it is a ECMAScript object or not 135 * @return tells whether given object is a ECMAScript object or not. 136 */ 137 @Function(attributes = Attribute.NOT_ENUMERABLE, where = Where.CONSTRUCTOR) 138 public static boolean isScriptObject(final Object self, final Object obj) { 139 return obj instanceof ScriptObject; 140 } 141 142 /** 143 * Returns true if the specified object is a ECMAScript function, that is an instance of {@link ScriptFunction}. 144 * @param self not used 145 * @param obj the object that is checked if it is a ECMAScript function or not 146 * @return tells whether given object is a ECMAScript function or not. 147 */ 148 @Function(attributes = Attribute.NOT_ENUMERABLE, where = Where.CONSTRUCTOR) 149 public static boolean isScriptFunction(final Object self, final Object obj) { 150 return obj instanceof ScriptFunction; 151 } 152 153 /** 154 * <p> 155 * Given a name of a Java type, returns an object representing that type in Nashorn. The Java class of the objects 156 * used to represent Java types in Nashorn is not {@link java.lang.Class} but rather {@link StaticClass}. They are 157 * the objects that you can use with the {@code new} operator to create new instances of the class as well as to 158 * access static members of the class. In Nashorn, {@code Class} objects are just regular Java objects that aren't 159 * treated specially. Instead of them, {@link StaticClass} instances - which we sometimes refer to as "Java type 160 * objects" are used as constructors with the {@code new} operator, and they expose static fields, properties, and 161 * methods. While this might seem confusing at first, it actually closely matches the Java language: you use a 162 * different expression (e.g. {@code java.io.File}) as an argument in "new" and to address statics, and it is 163 * distinct from the {@code Class} object (e.g. {@code java.io.File.class}). Below we cover in details the 164 * properties of the type objects. 165 * </p> 166 * <p><b>Constructing Java objects</b></p> 167 * Examples: 168 * <pre> 169 * var arrayListType = Java.type("java.util.ArrayList") 170 * var intType = Java.type("int") 171 * var stringArrayType = Java.type("java.lang.String[]") 172 * var int2DArrayType = Java.type("int[][]") 173 * </pre> 174 * Note that the name of the type is always a string for a fully qualified name. You can use any of these types to 175 * create new instances, e.g.: 176 * <pre> 177 * var anArrayList = new Java.type("java.util.ArrayList") 178 * </pre> 179 * or 180 * <pre> 181 * var ArrayList = Java.type("java.util.ArrayList") 182 * var anArrayList = new ArrayList 183 * var anArrayListWithSize = new ArrayList(16) 184 * </pre> 185 * In the special case of inner classes, you can either use the JVM fully qualified name, meaning using {@code $} 186 * sign in the class name, or you can use the dot: 187 * <pre> 188 * var ftype = Java.type("java.awt.geom.Arc2D$Float") 189 * </pre> 190 * and 191 * <pre> 192 * var ftype = Java.type("java.awt.geom.Arc2D.Float") 193 * </pre> 194 * both work. Note however that using the dollar sign is faster, as Java.type first tries to resolve the class name 195 * as it is originally specified, and the internal JVM names for inner classes use the dollar sign. If you use the 196 * dot, Java.type will internally get a ClassNotFoundException and subsequently retry by changing the last dot to 197 * dollar sign. As a matter of fact, it'll keep replacing dots with dollar signs until it either successfully loads 198 * the class or runs out of all dots in the name. This way it can correctly resolve and load even multiply nested 199 * inner classes with the dot notation. Again, this will be slower than using the dollar signs in the name. An 200 * alternative way to access the inner class is as a property of the outer class: 201 * <pre> 202 * var arctype = Java.type("java.awt.geom.Arc2D") 203 * var ftype = arctype.Float 204 * </pre> 205 * <p> 206 * You can access both static and non-static inner classes. If you want to create an instance of a non-static 207 * inner class, remember to pass an instance of its outer class as the first argument to the constructor. 208 * </p> 209 * <p> 210 * If the type is abstract, you can instantiate an anonymous subclass of it using an argument list that is 211 * applicable to any of its public or protected constructors, but inserting a JavaScript object with functions 212 * properties that provide JavaScript implementations of the abstract methods. If method names are overloaded, the 213 * JavaScript function will provide implementation for all overloads. E.g.: 214 * </p> 215 * <pre> 216 * var TimerTask = Java.type("java.util.TimerTask") 217 * var task = new TimerTask({ run: function() { print("Hello World!") } }) 218 * </pre> 219 * <p> 220 * Nashorn supports a syntactic extension where a "new" expression followed by an argument is identical to 221 * invoking the constructor and passing the argument to it, so you can write the above example also as: 222 * </p> 223 * <pre> 224 * var task = new TimerTask { 225 * run: function() { 226 * print("Hello World!") 227 * } 228 * } 229 * </pre> 230 * <p> 231 * which is very similar to Java anonymous inner class definition. On the other hand, if the type is an abstract 232 * type with a single abstract method (commonly referred to as a "SAM type") or all abstract methods it has share 233 * the same overloaded name), then instead of an object, you can just pass a function, so the above example can 234 * become even more simplified to: 235 * </p> 236 * <pre> 237 * var task = new TimerTask(function() { print("Hello World!") }) 238 * </pre> 239 * <p> 240 * Note that in every one of these cases if you are trying to instantiate an abstract class that has constructors 241 * that take some arguments, you can invoke those simply by specifying the arguments after the initial 242 * implementation object or function. 243 * </p> 244 * <p>The use of functions can be taken even further; if you are invoking a Java method that takes a SAM type, 245 * you can just pass in a function object, and Nashorn will know what you meant: 246 * </p> 247 * <pre> 248 * var timer = new Java.type("java.util.Timer") 249 * timer.schedule(function() { print("Hello World!") }) 250 * </pre> 251 * <p> 252 * Here, {@code Timer.schedule()} expects a {@code TimerTask} as its argument, so Nashorn creates an instance of a 253 * {@code TimerTask} subclass and uses the passed function to implement its only abstract method, {@code run()}. In 254 * this usage though, you can't use non-default constructors; the type must be either an interface, or must have a 255 * protected or public no-arg constructor. 256 * </p> 257 * <p> 258 * You can also subclass non-abstract classes; for that you will need to use the {@link #extend(Object, Object...)} 259 * method. 260 * </p> 261 * <p><b>Accessing static members</b></p> 262 * Examples: 263 * <pre> 264 * var File = Java.type("java.io.File") 265 * var pathSep = File.pathSeparator 266 * var tmpFile1 = File.createTempFile("abcdefg", ".tmp") 267 * var tmpFile2 = File.createTempFile("abcdefg", ".tmp", new File("/tmp")) 268 * </pre> 269 * Actually, you can even assign static methods to variables, so the above example can be rewritten as: 270 * <pre> 271 * var File = Java.type("java.io.File") 272 * var createTempFile = File.createTempFile 273 * var tmpFile1 = createTempFile("abcdefg", ".tmp") 274 * var tmpFile2 = createTempFile("abcdefg", ".tmp", new File("/tmp")) 275 * </pre> 276 * If you need to access the actual {@code java.lang.Class} object for the type, you can use the {@code class} 277 * property on the object representing the type: 278 * <pre> 279 * var File = Java.type("java.io.File") 280 * var someFile = new File("blah") 281 * print(File.class === someFile.getClass()) // prints true 282 * </pre> 283 * Of course, you can also use the {@code getClass()} method or its equivalent {@code class} property on any 284 * instance of the class. Other way round, you can use the synthetic {@code static} property on any 285 * {@code java.lang.Class} object to retrieve its type-representing object: 286 * <pre> 287 * var File = Java.type("java.io.File") 288 * print(File.class.static === File) // prints true 289 * </pre> 290 * <p><b>{@code instanceof} operator</b></p> 291 * The standard ECMAScript {@code instanceof} operator is extended to recognize Java objects and their type objects: 292 * <pre> 293 * var File = Java.type("java.io.File") 294 * var aFile = new File("foo") 295 * print(aFile instanceof File) // prints true 296 * print(aFile instanceof File.class) // prints false - Class objects aren't type objects. 297 * </pre> 298 * @param self not used 299 * @param objTypeName the object whose JS string value represents the type name. You can use names of primitive Java 300 * types to obtain representations of them, and you can use trailing square brackets to represent Java array types. 301 * @return the object representing the named type 302 * @throws ClassNotFoundException if the class is not found 303 */ 304 @Function(attributes = Attribute.NOT_ENUMERABLE, where = Where.CONSTRUCTOR) 305 public static Object type(final Object self, final Object objTypeName) throws ClassNotFoundException { 306 return type(objTypeName); 307 } 308 309 private static StaticClass type(final Object objTypeName) throws ClassNotFoundException { 310 return StaticClass.forClass(type(JSType.toString(objTypeName))); 311 } 312 313 private static Class<?> type(final String typeName) throws ClassNotFoundException { 314 if (typeName.endsWith("[]")) { 315 return arrayType(typeName); 316 } 317 318 return simpleType(typeName); 319 } 320 321 /** 322 * Returns name of a java type {@link StaticClass}. 323 * @param self not used 324 * @param type the type whose name is returned 325 * @return name of the given type 326 */ 327 @Function(attributes = Attribute.NOT_ENUMERABLE, where = Where.CONSTRUCTOR) 328 public static Object typeName(final Object self, final Object type) { 329 if (type instanceof StaticClass) { 330 return ((StaticClass)type).getRepresentedClass().getName(); 331 } else if (type instanceof Class) { 332 return ((Class<?>)type).getName(); 333 } else { 334 return UNDEFINED; 335 } 336 } 337 338 /** 339 * Given a script object and a Java type, converts the script object into the desired Java type. Currently it 340 * performs shallow creation of Java arrays, as well as wrapping of objects in Lists and Dequeues. Example: 341 * <pre> 342 * var anArray = [1, "13", false] 343 * var javaIntArray = Java.to(anArray, "int[]") 344 * print(javaIntArray[0]) // prints 1 345 * print(javaIntArray[1]) // prints 13, as string "13" was converted to number 13 as per ECMAScript ToNumber conversion 346 * print(javaIntArray[2]) // prints 0, as boolean false was converted to number 0 as per ECMAScript ToNumber conversion 347 * </pre> 348 * @param self not used 349 * @param obj the script object. Can be null. 350 * @param objType either a {@link #type(Object, Object) type object} or a String describing the type of the Java 351 * object to create. Can not be null. If undefined, a "default" conversion is presumed (allowing the argument to be 352 * omitted). 353 * @return a Java object whose value corresponds to the original script object's value. Specifically, for array 354 * target types, returns a Java array of the same type with contents converted to the array's component type. Does 355 * not recursively convert for multidimensional arrays. For {@link List} or {@link Deque}, returns a live wrapper 356 * around the object, see {@link ListAdapter} for details. Returns null if obj is null. 357 * @throws ClassNotFoundException if the class described by objType is not found 358 */ 359 @Function(attributes = Attribute.NOT_ENUMERABLE, where = Where.CONSTRUCTOR) 360 public static Object to(final Object self, final Object obj, final Object objType) throws ClassNotFoundException { 361 if (obj == null) { 362 return null; 363 } 364 365 if (!(obj instanceof ScriptObject) && !(obj instanceof JSObject)) { 366 throw typeError("not.an.object", ScriptRuntime.safeToString(obj)); 367 } 368 369 final Class<?> targetClass; 370 if(objType == UNDEFINED) { 371 targetClass = Object[].class; 372 } else { 373 final StaticClass targetType; 374 if(objType instanceof StaticClass) { 375 targetType = (StaticClass)objType; 376 } else { 377 targetType = type(objType); 378 } 379 targetClass = targetType.getRepresentedClass(); 380 } 381 382 if(targetClass.isArray()) { 383 return JSType.toJavaArray(obj, targetClass.getComponentType()); 384 } 385 386 if(targetClass == List.class || targetClass == Deque.class) { 387 return ListAdapter.create(obj); 388 } 389 390 throw typeError("unsupported.java.to.type", targetClass.getName()); 391 } 392 393 /** 394 * Given a Java array or {@link Collection}, returns a JavaScript array with a shallow copy of its contents. Note 395 * that in most cases, you can use Java arrays and lists natively in Nashorn; in cases where for some reason you 396 * need to have an actual JavaScript native array (e.g. to work with the array comprehensions functions), you will 397 * want to use this method. Example: 398 * <pre> 399 * var File = Java.type("java.io.File") 400 * var listHomeDir = new File("~").listFiles() 401 * var jsListHome = Java.from(listHomeDir) 402 * var jpegModifiedDates = jsListHome 403 * .filter(function(val) { return val.getName().endsWith(".jpg") }) 404 * .map(function(val) { return val.lastModified() }) 405 * </pre> 406 * @param self not used 407 * @param objArray the java array or collection. Can be null. 408 * @return a JavaScript array with the copy of Java array's or collection's contents. Returns null if objArray is 409 * null. 410 */ 411 @Function(attributes = Attribute.NOT_ENUMERABLE, where = Where.CONSTRUCTOR) 412 public static NativeArray from(final Object self, final Object objArray) { 413 if (objArray == null) { 414 return null; 415 } else if (objArray instanceof Collection) { 416 return new NativeArray(((Collection<?>)objArray).toArray()); 417 } else if (objArray instanceof Object[]) { 418 return new NativeArray(((Object[])objArray).clone()); 419 } else if (objArray instanceof int[]) { 420 return new NativeArray(((int[])objArray).clone()); 421 } else if (objArray instanceof double[]) { 422 return new NativeArray(((double[])objArray).clone()); 423 } else if (objArray instanceof long[]) { 424 return new NativeArray(((long[])objArray).clone()); 425 } else if (objArray instanceof byte[]) { 426 return new NativeArray(copyArray((byte[])objArray)); 427 } else if (objArray instanceof short[]) { 428 return new NativeArray(copyArray((short[])objArray)); 429 } else if (objArray instanceof char[]) { 430 return new NativeArray(copyArray((char[])objArray)); 431 } else if (objArray instanceof float[]) { 432 return new NativeArray(copyArray((float[])objArray)); 433 } else if (objArray instanceof boolean[]) { 434 return new NativeArray(copyArray((boolean[])objArray)); 435 } 436 437 throw typeError("cant.convert.to.javascript.array", objArray.getClass().getName()); 438 } 439 440 private static int[] copyArray(final byte[] in) { 441 final int[] out = new int[in.length]; 442 for(int i = 0; i < in.length; ++i) { 443 out[i] = in[i]; 444 } 445 return out; 446 } 447 448 private static int[] copyArray(final short[] in) { 449 final int[] out = new int[in.length]; 450 for(int i = 0; i < in.length; ++i) { 451 out[i] = in[i]; 452 } 453 return out; 454 } 455 456 private static int[] copyArray(final char[] in) { 457 final int[] out = new int[in.length]; 458 for(int i = 0; i < in.length; ++i) { 459 out[i] = in[i]; 460 } 461 return out; 462 } 463 464 private static double[] copyArray(final float[] in) { 465 final double[] out = new double[in.length]; 466 for(int i = 0; i < in.length; ++i) { 467 out[i] = in[i]; 468 } 469 return out; 470 } 471 472 private static Object[] copyArray(final boolean[] in) { 473 final Object[] out = new Object[in.length]; 474 for(int i = 0; i < in.length; ++i) { 475 out[i] = in[i]; 476 } 477 return out; 478 } 479 480 private static Class<?> simpleType(final String typeName) throws ClassNotFoundException { 481 final Class<?> primClass = TypeUtilities.getPrimitiveTypeByName(typeName); 482 if(primClass != null) { 483 return primClass; 484 } 485 final Context ctx = Global.getThisContext(); 486 try { 487 return ctx.findClass(typeName); 488 } catch(final ClassNotFoundException e) { 489 // The logic below compensates for a frequent user error - when people use dot notation to separate inner 490 // class names, i.e. "java.lang.Character.UnicodeBlock" vs."java.lang.Character$UnicodeBlock". The logic 491 // below will try alternative class names, replacing dots at the end of the name with dollar signs. 492 final StringBuilder nextName = new StringBuilder(typeName); 493 int lastDot = nextName.length(); 494 for(;;) { 495 lastDot = nextName.lastIndexOf(".", lastDot - 1); 496 if(lastDot == -1) { 497 // Exhausted the search space, class not found - rethrow the original exception. 498 throw e; 499 } 500 nextName.setCharAt(lastDot, '$'); 501 try { 502 return ctx.findClass(nextName.toString()); 503 } catch(final ClassNotFoundException cnfe) { 504 // Intentionally ignored, so the loop retries with the next name 505 } 506 } 507 } 508 509 } 510 511 private static Class<?> arrayType(final String typeName) throws ClassNotFoundException { 512 return Array.newInstance(type(typeName.substring(0, typeName.length() - 2)), 0).getClass(); 513 } 514 515 /** 516 * Returns a type object for a subclass of the specified Java class (or implementation of the specified interface) 517 * that acts as a script-to-Java adapter for it. See {@link #type(Object, Object)} for a discussion of type objects, 518 * and see {@link JavaAdapterFactory} for details on script-to-Java adapters. Note that you can also implement 519 * interfaces and subclass abstract classes using {@code new} operator on a type object for an interface or abstract 520 * class. However, to extend a non-abstract class, you will have to use this method. Example: 521 * <pre> 522 * var ArrayList = Java.type("java.util.ArrayList") 523 * var ArrayListExtender = Java.extend(ArrayList) 524 * var printSizeInvokedArrayList = new ArrayListExtender() { 525 * size: function() { print("size invoked!"); } 526 * } 527 * var printAddInvokedArrayList = new ArrayListExtender() { 528 * add: function(x, y) { 529 * if(typeof(y) === "undefined") { 530 * print("add(e) invoked!"); 531 * } else { 532 * print("add(i, e) invoked!"); 533 * } 534 * } 535 * </pre> 536 * We can see several important concepts in the above example: 537 * <ul> 538 * <li>Every specified list of Java types will have one extender subclass in Nashorn per caller protection domain - 539 * repeated invocations of {@code extend} for the same list of types for scripts same protection domain will yield 540 * the same extender type. It's a generic adapter that delegates to whatever JavaScript functions its implementation 541 * object has on a per-instance basis.</li> 542 * <li>If the Java method is overloaded (as in the above example {@code List.add()}), then your JavaScript adapter 543 * must be prepared to deal with all overloads.</li> 544 * <li>To invoke super methods from adapters, call them on the adapter instance prefixing them with {@code super$}, 545 * or use the special {@link #_super(Object, Object) super-adapter}.</li> 546 * <li>It is also possible to specify an ordinary JavaScript object as the last argument to {@code extend}. In that 547 * case, it is treated as a class-level override. {@code extend} will return an extender class where all instances 548 * will have the methods implemented by functions on that object, just as if that object were passed as the last 549 * argument to their constructor. Example: 550 * <pre> 551 * var Runnable = Java.type("java.lang.Runnable") 552 * var R1 = Java.extend(Runnable, { 553 * run: function() { 554 * print("R1.run() invoked!") 555 * } 556 * }) 557 * var r1 = new R1 558 * var t = new java.lang.Thread(r1) 559 * t.start() 560 * t.join() 561 * </pre> 562 * As you can see, you don't have to pass any object when you create a new instance of {@code R1} as its 563 * {@code run()} function was defined already when extending the class. If you also want to add instance-level 564 * overrides on these objects, you will have to repeatedly use {@code extend()} to subclass the class-level adapter. 565 * For such adapters, the order of precedence is instance-level method, class-level method, superclass method, or 566 * {@code UnsupportedOperationException} if the superclass method is abstract. If we continue our previous example: 567 * <pre> 568 * var R2 = Java.extend(R1); 569 * var r2 = new R2(function() { print("r2.run() invoked!") }) 570 * r2.run() 571 * </pre> 572 * We'll see it'll print {@code "r2.run() invoked!"}, thus overriding on instance-level the class-level behavior. 573 * Note that you must use {@code Java.extend} to explicitly create an instance-override adapter class from a 574 * class-override adapter class, as the class-override adapter class is no longer abstract. 575 * </li> 576 * </ul> 577 * @param self not used 578 * @param types the original types. The caller must pass at least one Java type object of class {@link StaticClass} 579 * representing either a public interface or a non-final public class with at least one public or protected 580 * constructor. If more than one type is specified, at most one can be a class and the rest have to be interfaces. 581 * Invoking the method twice with exactly the same types in the same order - in absence of class-level overrides - 582 * will return the same adapter class, any reordering of types or even addition or removal of redundant types (i.e. 583 * interfaces that other types in the list already implement/extend, or {@code java.lang.Object} in a list of types 584 * consisting purely of interfaces) will result in a different adapter class, even though those adapter classes are 585 * functionally identical; we deliberately don't want to incur the additional processing cost of canonicalizing type 586 * lists. As a special case, the last argument can be a {@code ScriptObject} instead of a type. In this case, a 587 * separate adapter class is generated - new one for each invocation - that will use the passed script object as its 588 * implementation for all instances. Instances of such adapter classes can then be created without passing another 589 * script object in the constructor, as the class has a class-level behavior defined by the script object. However, 590 * you can still pass a script object (or if it's a SAM type, a function) to the constructor to provide further 591 * instance-level overrides. 592 * 593 * @return a new {@link StaticClass} that represents the adapter for the original types. 594 */ 595 @Function(attributes = Attribute.NOT_ENUMERABLE, where = Where.CONSTRUCTOR) 596 public static Object extend(final Object self, final Object... types) { 597 if(types == null || types.length == 0) { 598 throw typeError("extend.expects.at.least.one.argument"); 599 } 600 final int l = types.length; 601 final int typesLen; 602 final ScriptObject classOverrides; 603 if(types[l - 1] instanceof ScriptObject) { 604 classOverrides = (ScriptObject)types[l - 1]; 605 typesLen = l - 1; 606 if(typesLen == 0) { 607 throw typeError("extend.expects.at.least.one.type.argument"); 608 } 609 } else { 610 classOverrides = null; 611 typesLen = l; 612 } 613 final Class<?>[] stypes = new Class<?>[typesLen]; 614 try { 615 for(int i = 0; i < typesLen; ++i) { 616 stypes[i] = ((StaticClass)types[i]).getRepresentedClass(); 617 } 618 } catch(final ClassCastException e) { 619 throw typeError("extend.expects.java.types"); 620 } 621 // Note that while the public API documentation claims self is not used, we actually use it. 622 // ScriptFunction.findCallMethod will bind the lookup object into it, and we can then use that lookup when 623 // requesting the adapter class. Note that if Java.extend is invoked with no lookup object, it'll pass the 624 // public lookup which'll result in generation of a no-permissions adapter. A typical situation this can happen 625 // is when the extend function is bound. 626 final MethodHandles.Lookup lookup; 627 if(self instanceof MethodHandles.Lookup) { 628 lookup = (MethodHandles.Lookup)self; 629 } else { 630 lookup = MethodHandles.publicLookup(); 631 } 632 return JavaAdapterFactory.getAdapterClassFor(stypes, classOverrides, lookup); 633 } 634 635 /** 636 * When given an object created using {@code Java.extend()} or equivalent mechanism (that is, any JavaScript-to-Java 637 * adapter), returns an object that can be used to invoke superclass methods on that object. E.g.: 638 * <pre> 639 * var cw = new FilterWriterAdapter(sw) { 640 * write: function(s, off, len) { 641 * s = capitalize(s, off, len) 642 * cw_super.write(s, 0, s.length()) 643 * } 644 * } 645 * var cw_super = Java.super(cw) 646 * </pre> 647 * @param self the {@code Java} object itself - not used. 648 * @param adapter the original Java adapter instance for which the super adapter is created. 649 * @return a super adapter for the original adapter 650 */ 651 @Function(attributes = Attribute.NOT_ENUMERABLE, where = Where.CONSTRUCTOR, name="super") 652 public static Object _super(final Object self, final Object adapter) { 653 return Bootstrap.createSuperAdapter(adapter); 654 } 655} 656