Closure.hx 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. package jvm;
  2. import java.NativeArray;
  3. import java.lang.reflect.Method;
  4. @:native("haxe.jvm.Closure")
  5. @:nativeGen
  6. @:keep
  7. class Closure extends ClosureDispatch {
  8. public var context:Dynamic;
  9. public var method:Method;
  10. var isStatic:Bool;
  11. var params:NativeArray<java.lang.Class<Dynamic>>;
  12. public function new(context:Null<Dynamic>, method:Method) {
  13. super();
  14. this.context = context;
  15. this.method = method;
  16. isStatic = method.getModifiers() & java.lang.reflect.Modifier.STATIC != 0;
  17. params = method.getParameterTypes();
  18. }
  19. public function bindTo(context:Dynamic) {
  20. return new Closure(context, method);
  21. }
  22. override public function equals(other:java.lang.Object) {
  23. if (!Jvm.instanceof(other, Closure)) {
  24. return false;
  25. }
  26. var other:Closure = cast other;
  27. return context == other.context && method == other.method;
  28. }
  29. public override function invokeDynamic(args:NativeArray<Dynamic>):Dynamic {
  30. if (isStatic && context != null) {
  31. var newArgs = new NativeArray(args.length + 1);
  32. haxe.ds.Vector.blit(cast args, 0, cast newArgs, 1, args.length);
  33. newArgs[0] = context;
  34. args = newArgs;
  35. }
  36. var args = switch (jvm.Jvm.unifyCallArguments(args, params, true)) {
  37. case Some(args):
  38. args;
  39. case None:
  40. args;
  41. };
  42. try {
  43. return method.invoke(context, args);
  44. } catch (e:java.lang.reflect.InvocationTargetException) {
  45. throw e.getCause();
  46. }
  47. }
  48. }
  49. @:native("haxe.jvm.ClosureDispatch")
  50. extern class ClosureDispatch extends Function {}
  51. @:native("haxe.jvm.VarArgs")
  52. extern class VarArgs extends Function {
  53. var func:Function;
  54. public function new(func:Function):Void;
  55. }