jni_helper.dart 22.8 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
// Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

part of dart_jni;

class JavaError extends Error {
  JavaError(this._message);
  String _message;
  String toString() => _message;
}

// JNI methods used to invoke Java reflection
class _JavaReflect {
  JniClass classClazz;
  int classForName;
  int classGetConstructors;
  int classGetFields;
  int classGetMethods;
  int classGetName;
  int constructorGetParameterTypes;
  int fieldGetType;
  int memberGetModifiers;
  int memberGetName;
  int methodGetParameterTypes;
  int methodGetReturnType;
  int objectGetClass;
  int objectToString;
29
  JniClass stringClazz;
30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66

  int modifierStatic;

  _JavaReflect() {
    classClazz = JniClass.fromName('java.lang.Class');
    classForName = classClazz.getStaticMethodId('forName',
        '(Ljava/lang/String;ZLjava/lang/ClassLoader;)Ljava/lang/Class;');
    classGetConstructors = classClazz.getMethodId('getConstructors',
        '()[Ljava/lang/reflect/Constructor;');
    classGetFields = classClazz.getMethodId('getFields', '()[Ljava/lang/reflect/Field;');
    classGetMethods = classClazz.getMethodId('getMethods', '()[Ljava/lang/reflect/Method;');
    classGetName = classClazz.getMethodId('getName', '()Ljava/lang/String;');

    JniClass constructorClazz = JniClass.fromName('java.lang.reflect.Constructor');
    constructorGetParameterTypes = constructorClazz.getMethodId(
        'getParameterTypes', '()[Ljava/lang/Class;');

    JniClass fieldClazz = JniClass.fromName('java.lang.reflect.Field');
    fieldGetType = fieldClazz.getMethodId('getType', '()Ljava/lang/Class;');

    JniClass memberClazz = JniClass.fromName('java.lang.reflect.Member');
    memberGetModifiers = memberClazz.getMethodId('getModifiers', '()I');
    memberGetName = memberClazz.getMethodId('getName', '()Ljava/lang/String;');

    JniClass methodClazz = JniClass.fromName('java.lang.reflect.Method');
    methodGetParameterTypes = methodClazz.getMethodId(
        'getParameterTypes', '()[Ljava/lang/Class;');
    methodGetReturnType = methodClazz.getMethodId(
        'getReturnType', '()Ljava/lang/Class;');

    JniClass modifierClazz = JniClass.fromName('java.lang.reflect.Modifier');
    modifierStatic = modifierClazz.getStaticIntField(
        modifierClazz.getStaticFieldId('STATIC', 'I'));

    JniClass objectClazz = JniClass.fromName('java.lang.Object');
    objectGetClass = objectClazz.getMethodId('getClass', '()Ljava/lang/Class;');
    objectToString = objectClazz.getMethodId('toString', '()Ljava/lang/String;');
67 68

    stringClazz = JniClass.fromName('java.lang.String');
69 70 71 72 73 74 75
  }
}

final _JavaReflect _reflect = new _JavaReflect();

class _JavaType {
  final String name;
76 77 78 79 80
  final JniClass clazz;
  final bool isPrimitive;

  _JavaType(this.name, this.clazz)
      : isPrimitive = false;
81

82 83 84
  _JavaType._primitive(this.name)
      : clazz = null,
        isPrimitive = true;
85 86 87 88 89

  String toString() => 'JavaType:$name';
}

class _JavaPrimitive {
90 91 92 93 94 95 96 97 98
  static final _JavaType jvoid = new _JavaType._primitive('void');
  static final _JavaType jboolean = new _JavaType._primitive('boolean');
  static final _JavaType jbyte = new _JavaType._primitive('byte');
  static final _JavaType jchar = new _JavaType._primitive('char');
  static final _JavaType jshort = new _JavaType._primitive('short');
  static final _JavaType jint = new _JavaType._primitive('int');
  static final _JavaType jlong = new _JavaType._primitive('long');
  static final _JavaType jfloat = new _JavaType._primitive('float');
  static final _JavaType jdouble = new _JavaType._primitive('double');
99 100
}

101
final Map<String, _JavaType> _typeCache = <String, _JavaType>{
102 103 104 105 106 107 108 109 110 111 112
  'void': _JavaPrimitive.jvoid,
  'boolean': _JavaPrimitive.jboolean,
  'byte': _JavaPrimitive.jbyte,
  'char': _JavaPrimitive.jchar,
  'short': _JavaPrimitive.jshort,
  'int': _JavaPrimitive.jint,
  'long': _JavaPrimitive.jlong,
  'float': _JavaPrimitive.jfloat,
  'double': _JavaPrimitive.jdouble,
};

113
_JavaType _javaTypeForClass(JniClass clazz) {
114 115
  String className = JniString.unwrap(clazz.callObjectMethod(_reflect.classGetName, []));

116 117 118
  _JavaType type = _typeCache[className];
  if (type != null)
    return type;
119

120 121 122
  type = new _JavaType(className, clazz);
  _typeCache[className] = type;
  return type;
123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144
}

class _JavaField {
  String name;
  int fieldId;
  _JavaType type;
  int modifiers;

  _JavaField(JniObject field) {
    name = JniString.unwrap(field.callObjectMethod(_reflect.memberGetName, []));
    fieldId = JniApi.fromReflectedField(field);
    type = _javaTypeForClass(
        field.callObjectMethod(_reflect.fieldGetType, []));
    modifiers = field.callIntMethod(_reflect.memberGetModifiers, []);
  }

  bool get isStatic => (modifiers & _reflect.modifierStatic) != 0;
}

abstract class _HasArguments {
  String get name;
  List<_JavaType> get argTypes;
145
  int get methodId;
146 147 148 149
}

class _JavaMethod implements _HasArguments {
  String _name;
150
  int _methodId;
151 152 153 154 155 156
  _JavaType returnType;
  int modifiers;
  List<_JavaType> _argTypes;

  _JavaMethod(JniObject method) {
    _name = JniString.unwrap(method.callObjectMethod(_reflect.memberGetName, []));
157
    _methodId = JniApi.fromReflectedMethod(method);
158 159 160 161 162 163 164 165 166 167 168 169 170
    returnType = _javaTypeForClass(
        method.callObjectMethod(_reflect.methodGetReturnType, []));
    modifiers = method.callIntMethod(_reflect.memberGetModifiers, []);

    JniObjectArray argClasses = method.callObjectMethod(_reflect.methodGetParameterTypes, []);
    _argTypes = new List<_JavaType>();
    for (JniObject argClass in argClasses) {
      _argTypes.add(_javaTypeForClass(argClass));
    }
  }

  String get name => _name;
  List<_JavaType> get argTypes => _argTypes;
171
  int get methodId => _methodId;
172 173 174 175 176 177

  bool get isStatic => (modifiers & _reflect.modifierStatic) != 0;
}

class _JavaConstructor implements _HasArguments {
  String _name;
178
  int _methodId;
179 180 181 182
  List<_JavaType> _argTypes;

  _JavaConstructor(JniObject ctor) {
    _name = JniString.unwrap(ctor.callObjectMethod(_reflect.memberGetName, []));
183
    _methodId = JniApi.fromReflectedMethod(ctor);
184 185 186 187 188 189 190 191 192 193 194

    JniObjectArray argClasses = ctor.callObjectMethod(
        _reflect.constructorGetParameterTypes, []);
    _argTypes = new List<_JavaType>();
    for (JniObject argClass in argClasses) {
      _argTypes.add(_javaTypeForClass(argClass));
    }
  }

  String get name => _name;
  List<_JavaType> get argTypes => _argTypes;
195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224
  int get methodId => _methodId;
}

// Determines whether a Dart value can be used as a method argument declared as
// the given Java type.
bool _typeCompatible(dynamic value, _JavaType type) {
  if (type.isPrimitive) {
    if (type == _JavaPrimitive.jboolean) {
      return (value is bool);
    } else {
      return (value is num || value is bool || value is JniFloat);
    }
  }

  if (value == null)
    return true;

  if (value is JavaObject)
    return value.javaClass.jniClass.isAssignable(type.clazz);

  if (value is JniObject)
    return value.getObjectClass().isAssignable(type.clazz);

  if (value is String) {
    if (type.isPrimitive)
      return false;
    return _reflect.stringClazz.isAssignable(type.clazz);
  }

  return false;
225 226 227 228 229
}

// Given a list of overloaded methods, select one that is the best match for
// the provided arguments.
_HasArguments _findMatchingMethod(List<_HasArguments> overloads, List args) {
230 231 232 233
  List<_HasArguments> matches = new List<_HasArguments>();
  for (_HasArguments overload in overloads) {
    if (overload.argTypes.length == args.length)
      matches.add(overload);
234 235
  }

236 237 238 239 240 241 242 243 244 245
  if (matches.length == 1)
    return matches[0];

  if (matches.isEmpty)
    throw new JavaError('Argument mismatch when invoking method ${overloads[0].name}');

  outer: for (_HasArguments match in matches) {
    for (int i = 0; i < args.length; i++) {
      if (!_typeCompatible(args[i], match.argTypes[i]))
        continue outer;
246
    }
247
    return match;
248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263
  }

  throw new JavaError('Unable to find matching method for ${overloads[0].name}');
}

// Convert an object received from JNI into the corresponding Dart type.
dynamic _javaObjectToDart(JniObject object) {
  if (object == null)
    return null;

  if (object is JniString)
    return object.text;

  if (object is JniClass)
    return Java.wrapClassObject(object);

264 265 266
  if (object is JniArray)
    return object;

267 268 269 270
  return new JavaObject(object);
}

// Convert a Dart object to a type suitable for passing to JNI.
271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290
dynamic _dartObjectToJava(dynamic object, _JavaType javaType) {
  if (javaType.isPrimitive) {
    if (javaType == _JavaPrimitive.jboolean) {
      if (object is bool)
        return object;
      throw new JavaError('Unable to convert Dart object to Java boolean: $object');
    }
    if (javaType == _JavaPrimitive.jfloat) {
      if (object is JniFloat)
        return object;
      if (object is num)
        return new JniFloat(object);
      throw new JavaError('Unable to convert Dart object to Java float: $object');
    }

    if (object is num)
      return object;
    throw new JavaError('Unable to convert Dart object to Java primitive type: $object');
  }

291 292 293 294 295 296 297 298 299 300 301 302 303 304 305
  if (object == null)
    return object;

  if (object is JniObject)
    return object;

  if (object is JavaObject)
    return object.jniObject;

  if (object is String)
    return JniString.create(object);

  throw new JavaError('Unable to convert Dart object to Java: $object');
}

306 307 308 309 310 311 312 313
List _convertArgumentsToJava(List dartArgs, _HasArguments method) {
  List result = new List();
  for (int i = 0; i < dartArgs.length; i++) {
    result.add(_dartObjectToJava(dartArgs[i], method.argTypes[i]));
  }
  return result;
}

314
/// A class that provides access to Java objects from within Dart.
315 316 317
class Java {
  static final Map<String, JavaClass> _classCache = new Map<String, JavaClass>();

318
  /// Returns a [JavaClass] for the given class name.
319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334
  static JavaClass getClass(String className) {
    JavaClass cacheEntry = _classCache[className];
    if (cacheEntry != null)
      return cacheEntry;

    // Load and initialize the class
    JniClass jniClass = _reflect.classClazz.callStaticObjectMethod(
        _reflect.classForName,
        [className, true, JniApi.getClassLoader()]
    );

    JavaClass javaClass = new JavaClass._(jniClass);
    _classCache[javaClass.className] = javaClass;
    return javaClass;
  }

335
  /// Returns a [JavaClass] that wraps a raw JNI class object.
336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356
  static JavaClass wrapClassObject(dynamic classObject) {
    JniClass jniClass;
    if (classObject is JniClass) {
      jniClass = classObject;
    } else if (classObject is JavaObject && classObject.jniObject is JniClass) {
      jniClass = classObject.jniObject;
    } else {
      throw new JavaError('fromClassObject: $classObject is not a Java class');
    }

    String className = JniString.unwrap(jniClass.callObjectMethod(_reflect.classGetName, []));
    JavaClass cacheEntry = _classCache[className];
    if (cacheEntry != null)
      return cacheEntry;

    JavaClass javaClass = new JavaClass._(jniClass);
    _classCache[javaClass.className] = javaClass;
    return javaClass;
  }
}

357 358
/// A wrapper for a JNI class that uses reflection to provide access to the
/// class' static fields, methods, and constructors.
359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411
class JavaClass {
  JniClass _clazz;
  String _className;
  Map<Symbol, _JavaField> _fields;
  Map<Symbol, _JavaField> _staticFields;
  Map<Symbol, List<_JavaMethod>> _methods;
  Map<Symbol, List<_JavaMethod>> _staticMethods;
  List<_JavaConstructor> _constructors;

  static final Symbol _newInstanceSymbol = new Symbol('newInstance');

  JavaClass._(JniClass classObject) {
    _clazz = classObject;
    _className = JniString.unwrap(_clazz.callObjectMethod(_reflect.classGetName, []));

    _fields = new Map<Symbol, _JavaField>();
    _staticFields = new Map<Symbol, _JavaField>();
    JniObjectArray reflectFields = _clazz.callObjectMethod(_reflect.classGetFields, []);
    for (JniObject reflectField in reflectFields) {
      _JavaField javaField = new _JavaField(reflectField);
      Map<Symbol, _JavaField> fieldMap =
          javaField.isStatic ? _staticFields : _fields;
      fieldMap[new Symbol(javaField.name)] = javaField;

      // Dart will identify the field setter with a symbol name ending with an equal sign.
      fieldMap[new Symbol(javaField.name + '=')] = javaField;
    }

    _methods = new Map<Symbol, List<_JavaMethod>>();
    _staticMethods = new Map<Symbol, List<_JavaMethod>>();
    JniObjectArray reflectMethods = _clazz.callObjectMethod(_reflect.classGetMethods, []);
    for (JniObject reflectMethod in reflectMethods) {
      _JavaMethod javaMethod = new _JavaMethod(reflectMethod);
      Map<Symbol, List<_JavaMethod>> methodMap =
          javaMethod.isStatic ? _staticMethods : _methods;
      Symbol symbol = new Symbol(javaMethod.name);
      List<_JavaMethod> overloads = methodMap[symbol];
      if (overloads != null) {
        overloads.add(javaMethod);
      } else {
        methodMap[symbol] = <_JavaMethod>[javaMethod];
      }
    }

    _constructors = new List<_JavaConstructor>();
    JniObjectArray reflectCtors = _clazz.callObjectMethod(_reflect.classGetConstructors, []);
    for (JniObject ctor in reflectCtors) {
      _constructors.add(new _JavaConstructor(ctor));
    }
  }

  String toString() => 'JavaClass:$_className';

412
  /// The name of the wrapped Java class.
413 414
  String get className => _className;

415
  /// A raw [JniClass] representing the java.lang.Class instance for this class
416 417
  JniClass get jniClass => _clazz;

418
  /// A [JavaObject] representing the java.lang.Class instance for this class
419 420 421 422
  JavaObject get asJavaObject => new JavaObject(_clazz);

  dynamic noSuchMethod(Invocation invocation) {
    if (invocation.isMethod) {
423 424 425 426 427 428 429 430
      List<_HasArguments> overloads;
      bool isConstructor = (invocation.memberName == _newInstanceSymbol);
      if (isConstructor) {
        overloads = _constructors;
      } else {
        overloads = _staticMethods[invocation.memberName];
        if (overloads == null)
          throw new JavaError('Static method ${invocation.memberName} not found');
431 432
      }

433 434
      _HasArguments method = _findMatchingMethod(overloads, invocation.positionalArguments);
      List args = _convertArgumentsToJava(invocation.positionalArguments, method);
435

436 437 438
      if (isConstructor) {
        return new JavaObject(_clazz.newObject(method.methodId, args));
      }
439

440 441
      _JavaType returnType = (method as _JavaMethod).returnType;
      if (returnType == _JavaPrimitive.jvoid) {
442
        return _clazz.callStaticVoidMethod(method.methodId, args);
443
      } else if (returnType == _JavaPrimitive.jboolean) {
444
        return _clazz.callStaticBooleanMethod(method.methodId, args);
445
      } else if (returnType == _JavaPrimitive.jbyte) {
446
        return _clazz.callStaticByteMethod(method.methodId, args);
447
      } else if (returnType == _JavaPrimitive.jchar) {
448
        return _clazz.callStaticCharMethod(method.methodId, args);
449
      } else if (returnType == _JavaPrimitive.jshort) {
450
        return _clazz.callStaticShortMethod(method.methodId, args);
451
      } else if (returnType == _JavaPrimitive.jint) {
452
        return _clazz.callStaticIntMethod(method.methodId, args);
453
      } else if (returnType == _JavaPrimitive.jlong) {
454
        return _clazz.callStaticLongMethod(method.methodId, args);
455
      } else if (returnType == _JavaPrimitive.jfloat) {
456
        return _clazz.callStaticFloatMethod(method.methodId, args);
457
      } else if (returnType == _JavaPrimitive.jdouble) {
458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514
        return _clazz.callStaticDoubleMethod(method.methodId, args);
      } else {
        return _javaObjectToDart(
            _clazz.callStaticObjectMethod(method.methodId, args));
      }
    }

    if (invocation.isGetter) {
      _JavaField field = _staticFields[invocation.memberName];
      if (field == null)
        throw new JavaError('Static field ${invocation.memberName} not found');

      if (field.type == _JavaPrimitive.jboolean) {
        return _clazz.getStaticBooleanField(field.fieldId);
      } else if (field.type == _JavaPrimitive.jbyte) {
        return _clazz.getStaticByteField(field.fieldId);
      } else if (field.type == _JavaPrimitive.jchar) {
        return _clazz.getStaticCharField(field.fieldId);
      } else if (field.type == _JavaPrimitive.jshort) {
        return _clazz.getStaticShortField(field.fieldId);
      } else if (field.type == _JavaPrimitive.jint) {
        return _clazz.getStaticIntField(field.fieldId);
      } else if (field.type == _JavaPrimitive.jlong) {
        return _clazz.getStaticLongField(field.fieldId);
      } else if (field.type == _JavaPrimitive.jfloat) {
        return _clazz.getStaticFloatField(field.fieldId);
      } else if (field.type == _JavaPrimitive.jdouble) {
        return _clazz.getStaticDoubleField(field.fieldId);
      } else {
        return _javaObjectToDart(_clazz.getStaticObjectField(field.fieldId));
      }
    }

    if (invocation.isSetter) {
      _JavaField field = _staticFields[invocation.memberName];
      if (field == null)
        throw new JavaError('Static field ${invocation.memberName} not found');

      dynamic value = invocation.positionalArguments[0];

      if (field.type == _JavaPrimitive.jboolean) {
        _clazz.setStaticBooleanField(field.fieldId, value);
      } else if (field.type == _JavaPrimitive.jbyte) {
        _clazz.setStaticByteField(field.fieldId, value);
      } else if (field.type == _JavaPrimitive.jchar) {
        _clazz.setStaticCharField(field.fieldId, value);
      } else if (field.type == _JavaPrimitive.jshort) {
        _clazz.setStaticShortField(field.fieldId, value);
      } else if (field.type == _JavaPrimitive.jint) {
        _clazz.setStaticIntField(field.fieldId, value);
      } else if (field.type == _JavaPrimitive.jlong) {
        _clazz.setStaticLongField(field.fieldId, value);
      } else if (field.type == _JavaPrimitive.jfloat) {
        _clazz.setStaticFloatField(field.fieldId, value);
      } else if (field.type == _JavaPrimitive.jdouble) {
        _clazz.setStaticDoubleField(field.fieldId, value);
      } else {
515
        _clazz.setStaticObjectField(field.fieldId, _dartObjectToJava(value, field.type));
516 517 518 519 520 521 522 523 524
      }

      return null;
    }

    throw new JavaError('Unable to access ${invocation.memberName}');
  }
}

525 526
/// A wrapper for a JNI object that provides access to the object's fields
/// and methods.
527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543
class JavaObject {
  JniObject _object;
  JavaClass _clazz;

  JavaObject(JniObject object) {
    _object = object;

    _clazz = Java.wrapClassObject(
        _object.callObjectMethod(_reflect.objectGetClass, []));
  }

  dynamic noSuchMethod(Invocation invocation) {
    if (invocation.isMethod) {
      List<_JavaMethod> overloads = _clazz._methods[invocation.memberName];
      if (overloads == null)
        throw new JavaError('Method ${invocation.memberName} not found');

544 545
      _JavaMethod method = _findMatchingMethod(overloads, invocation.positionalArguments);
      List args = _convertArgumentsToJava(invocation.positionalArguments, method);
546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620

      if (method.returnType == _JavaPrimitive.jvoid) {
        return _object.callVoidMethod(method.methodId, args);
      } else if (method.returnType == _JavaPrimitive.jboolean) {
        return _object.callBooleanMethod(method.methodId, args);
      } else if (method.returnType == _JavaPrimitive.jbyte) {
        return _object.callByteMethod(method.methodId, args);
      } else if (method.returnType == _JavaPrimitive.jchar) {
        return _object.callCharMethod(method.methodId, args);
      } else if (method.returnType == _JavaPrimitive.jshort) {
        return _object.callShortMethod(method.methodId, args);
      } else if (method.returnType == _JavaPrimitive.jint) {
        return _object.callIntMethod(method.methodId, args);
      } else if (method.returnType == _JavaPrimitive.jlong) {
        return _object.callLongMethod(method.methodId, args);
      } else if (method.returnType == _JavaPrimitive.jfloat) {
        return _object.callFloatMethod(method.methodId, args);
      } else if (method.returnType == _JavaPrimitive.jdouble) {
        return _object.callDoubleMethod(method.methodId, args);
      } else {
        return _javaObjectToDart(
            _object.callObjectMethod(method.methodId, args));
      }
    }

    if (invocation.isGetter) {
      _JavaField field = _clazz._fields[invocation.memberName];
      if (field == null)
        throw new JavaError('Field ${invocation.memberName} not found');

      if (field.type == _JavaPrimitive.jboolean) {
        return _object.getBooleanField(field.fieldId);
      } else if (field.type == _JavaPrimitive.jbyte) {
        return _object.getByteField(field.fieldId);
      } else if (field.type == _JavaPrimitive.jchar) {
        return _object.getCharField(field.fieldId);
      } else if (field.type == _JavaPrimitive.jshort) {
        return _object.getShortField(field.fieldId);
      } else if (field.type == _JavaPrimitive.jint) {
        return _object.getIntField(field.fieldId);
      } else if (field.type == _JavaPrimitive.jlong) {
        return _object.getLongField(field.fieldId);
      } else if (field.type == _JavaPrimitive.jfloat) {
        return _object.getFloatField(field.fieldId);
      } else if (field.type == _JavaPrimitive.jdouble) {
        return _object.getDoubleField(field.fieldId);
      } else {
        return _javaObjectToDart(_object.getObjectField(field.fieldId));
      }
    }

    if (invocation.isSetter) {
      _JavaField field = _clazz._fields[invocation.memberName];
      if (field == null)
        throw new JavaError('Field ${invocation.memberName} not found');

      dynamic value = invocation.positionalArguments[0];

      if (field.type == _JavaPrimitive.jboolean) {
        _object.setBooleanField(field.fieldId, value);
      } else if (field.type == _JavaPrimitive.jbyte) {
        _object.setByteField(field.fieldId, value);
      } else if (field.type == _JavaPrimitive.jchar) {
        _object.setCharField(field.fieldId, value);
      } else if (field.type == _JavaPrimitive.jshort) {
        _object.setShortField(field.fieldId, value);
      } else if (field.type == _JavaPrimitive.jint) {
        _object.setIntField(field.fieldId, value);
      } else if (field.type == _JavaPrimitive.jlong) {
        _object.setLongField(field.fieldId, value);
      } else if (field.type == _JavaPrimitive.jfloat) {
        _object.setFloatField(field.fieldId, value);
      } else if (field.type == _JavaPrimitive.jdouble) {
        _object.setDoubleField(field.fieldId, value);
      } else {
621
        _object.setObjectField(field.fieldId, _dartObjectToJava(value, field.type));
622 623 624 625 626 627 628 629
      }

      return null;
    }

    throw new JavaError('Unable to access ${invocation.memberName}');
  }

630
  /// Convert this object to a string using the Java object's `toString` method.
631
  String toString() {
632 633 634 635 636 637
    String result = JniString.unwrap(_object.callObjectMethod(_reflect.objectToString, []));
    if (!result.isEmpty) {
      return result;
    } else {
      return 'JavaObject(${_clazz.className})';
    }
638 639
  }

640
  /// A [JavaClass] representing this object's class.
641 642
  JavaClass get javaClass => _clazz;

643 644 645
  /// The raw [JniObject] wrapped by this object.
  /// This can be used to perform low-level JNI operations that aren't exposed
  /// by [JavaObject], such as access to specific overloaded methods.
646 647
  JniObject get jniObject => _object;
}