jni 0.22.4

Rust bindings to the JNI
Documentation
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
29
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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
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
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
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
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
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
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
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
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
use std::{
    convert::TryInto,
    marker::PhantomData,
    os::raw::{c_char, c_void},
    panic::{AssertUnwindSafe, catch_unwind, resume_unwind},
    ptr,
    sync::{Mutex, MutexGuard},
};

use jni_sys::jobject;

use crate::{
    DEFAULT_LOCAL_FRAME_CAPACITY, JNIVersion, JavaVM,
    descriptors::Desc,
    errors::*,
    jni_sig,
    objects::{
        Auto, AutoElements, AutoElementsCritical, Global, IntoAuto, JByteBuffer, JClass,
        JClassLoader, JFieldID, JList, JMap, JMethodID, JObject, JStaticFieldID, JStaticMethodID,
        JString, JThrowable, JValue, JValueOwned, ReleaseMode, TypeArray, Weak,
    },
    signature::{FieldSignature, JavaType, MethodSignature, Primitive},
    strings::{JNIStr, MUTF8Chars},
    sys::{
        self, JNINativeMethod, jboolean, jbyte, jchar, jdouble, jfloat, jint, jlong, jshort, jsize,
        jvalue,
    },
};
use crate::{
    errors::ErrorPolicy,
    objects::{
        Cast, JBooleanArray, JByteArray, JCharArray, JDoubleArray, JFloatArray, JIntArray,
        JLongArray, JObjectArray, JPrimitiveArray, JShortArray, LoaderContext,
        type_array_sealed::TypeArraySealed,
    },
};
use crate::{objects::AsJArrayRaw, signature::ReturnType};

use super::{AttachGuard, objects::Reference};

#[cfg(doc)]
use crate::{jni_str, objects::JThread, strings::JNIString};

/// A non-transparent wrapper around a raw [`sys::JNIEnv`] pointer that provides
/// safe access to the Java Native Interface (JNI) functions.
///
/// Since [Env] is not a type that is publicly constructible, you must obtain a
/// reference, either through a thread attachment, by upgrading an
/// [`EnvUnowned`] within a native method, or via the (unsafe)
/// [`AttachGuard::from_unowned`] APIs.
///
/// See:
/// - [`JavaVM::attach_current_thread`]
/// - [`JavaVM::attach_current_thread_for_scope`]
/// - [`JavaVM::with_local_frame`]
/// - [`JavaVM::with_top_local_frame`]
/// - [`EnvUnowned::with_env`]
///
/// [Env] is a non-transparent wrapper that is not FFI-safe, so it must not be
/// used to try and capture a raw [`sys::JNIEnv`] pointer passed to a native
/// method.
///
/// See [`EnvUnowned`] for a wrapper that is FFI-safe and can be used to capture
/// a `sys::JNIEnv` pointer passed to a native method.
///
/// # Overview of the API
///
/// All the [`Env`] methods aim to follow the JNI specification naming closely
/// enough to make it easier to map between the two. This means that method
/// names, parameter types, and return types will generally be consistent with
/// the JNI specification.
///
/// JNI APIs that can logically be thought of as methods, such as
/// `GetObjectArrayElement`, can be found as methods on the relevant Rust type,
/// in this case [`JObjectArray::get_element`].
///
/// # Exception handling
///
/// Since we're calling into the JVM with this, many methods also have the
/// potential to cause an exception to get thrown. If this is the case, an `Err`
/// result will be returned with the error kind [`Error::JavaException`]. Note
/// that this will _not_ clear the exception - it's up to the caller to decide
/// whether to do so or to let it continue being thrown.
///
/// # References and Lifetimes
///
/// As in C JNI, interactions with Java objects happen through
/// <dfn>references</dfn>, either local or global.
///
/// This crate provides various safe wrappers around JNI references, such as
/// [`JObject`], [`JClass`], [`JString`] and [`JList`] which all implement the
/// [`Reference`] trait.
///
/// By default these types represent <dfn>local references</dfn>, and they will
/// be associated with a lifetime that names the local reference frame they
/// belong to.
///
/// So for example `JObject<'local_1>`  and  `JObject<'local_2>` are local
/// reference that are owned by two different local reference frames and
/// although they may both be usable from a higher stack frame, it's not
/// possible to simply move ownership of a local reference from one local
/// reference frame to another.
///
/// A global reference can be represented by a [`Global`], which will wrap one
/// of the above primitive reference types like `Global<JObject<'static>>`. In
/// this case the `'static` lifetime indicates that the reference is not tied to
/// a local reference frame and can be used from any thread.
///
/// So long as there is at least one reference to a Java object, the JVM garbage
/// collector will not reclaim it.
///
/// <dfn>Global references</dfn> exist until deleted. Deletion occurs when the
/// `Global` is dropped.
///
/// <dfn>Local references</dfn> belong to a local reference frame, and exist
/// until [deleted][Env::delete_local_ref] or until the local reference frame is
/// exited. A new <dfn>local reference frame</dfn> is entered when a native
/// method is called from Java, or when Rust code does so explicitly using
/// [`Env::with_local_frame`]. That local reference frame is exited when the
/// native method or `with_local_frame` returns. When a local reference frame is
/// exited, all local references created inside it are deleted.
///
/// Unlike C JNI, this crate creates a separate `Env` for each local reference
/// frame. The associated Rust lifetime `'local` represents that local reference
/// frame. Rust's borrow checker will ensure that local references are not used
/// after their local reference frame exits (which would cause undefined
/// behavior).
///
/// Unlike global references, local references are not deleted when dropped by
/// default. This is for performance: it is faster for the JVM to delete all of
/// the local references in a frame all at once, than to delete each local
/// reference one at a time. However, this can cause a memory leak if the local
/// reference frame remains entered for a long time, such as a long-lasting
/// loop, in which case local references should be deleted explicitly. Local
/// references can be deleted when dropped if desired; use
/// [`Env::delete_local_ref`] or wrap with [`IntoAuto::auto`] to arrange that.
///
/// ## Lifetime Names
///
/// This crate uses the following convention for lifetime names:
///
/// * `'local` is the lifetime of a local reference frame, as described above.
///
/// * `'other_local`, `'other_local_1`, and `'other_local_2` are the lifetimes
///   of some other local reference frame, which may be but doesn't have to be
///   the same as `'local`. For example, [`Env::new_local_ref`] accepts a local
///   reference in any local reference frame `'other_local` and creates a new
///   local reference to the same object in `'local`.
///
/// * `'obj_ref` is the lifetime of a borrow of a JNI reference, like
///   <code>&amp;[JObject]</code> or <code>&amp;[Global]</code>. For example,
///   [`Env::get_list`] constructs a new [`JList`] that borrows a `&'obj_ref
///   JObject`.
///
/// ## `null` Java references
/// `null` Java references are handled by the following rules:
///   - Methods that require non-null references will return [Error::NullPtr] if
///     passed a `null` reference.
///   - If a JNI function returns `null` to indicate an error (e.g.
///     [`Env::new_int_array`]), it is converted to `Err`/[`Error::NullPtr`], or
///     some other more applicable error type, such as
///     [`Error::MethodNotFound`].
///   - Otherwise `null` is considered a valid Java reference and is represented
///     as [`JObject::null()`].
///
/// ## A `&mut Env` represents the top JNI stack frame
///
/// Each `Env<'local>` represents a single local reference frame in the JVM.
///
/// A **mutable** `&mut Env` is special: it always represents the *current top*
/// local reference frame on the JNI stack.
///
/// * You need `&mut Env` when creating new local references, since those can
///   only be created in the top frame.
/// * A shared `&Env` is fine for operations that don’t produce new local
///   references.
///
/// If you only have a shared `&Env` but need to create temporary local
/// references (that won’t escape the scope), you can materialize a new mutable
/// handle to the top frame using:
///
/// * [`Env::with_local_frame`] – pushes a new frame, returns a mutable `Env`
///   for it.
/// * [`Env::with_top_local_frame`] – borrows a mutable `Env` for the existing
///   top frame without pushing a new one.
///
/// If you don’t even have an `Env` (e.g. inside a `Drop` implementation), you
/// can still get one via:
///
/// * [`JavaVM::attach_current_thread`]
/// * [`JavaVM::with_top_local_frame`] - if you can guarantee that the thread is
///   already attached, and you just need a handle to the existing top frame.
///
/// (and you can access a [`JavaVM`] via [`JavaVM::singleton`]).
///
/// These APIs are safe because they constrain the new [`Env`] lifetime to the
/// scope of the call, so any references created cannot leak.
///
/// ## Runtime Top Frame Checks
///
/// Rust’s type system ensures that a mutable `Env<'local>` only produces
/// references tied to its frame.
///
/// Normally this crate also guarantees that a `&mut Env` represents the top
/// frame.
///
/// However, because the JVM is global and multiple crates may independently use
/// jni-rs, some valid usage patterns can be misused to create multiple mutable
/// `Env`s in the same scope. For example:
///
/// ```rust,no_run
/// # use jni::{JavaVM, errors::Result, objects::JString};
/// # fn f(vm: &JavaVM) -> Result<()> {
/// vm.attach_current_thread(|env1| -> Result<()> {
///     vm.attach_current_thread(|env2| -> Result<()> {
///         // env1 is still mutable, but no longer the top frame.
///         // This will panic at runtime:
///         JString::from_str(env1, "not valid here").unwrap();
///         Ok(())
///     })
/// })
/// # ; Ok(())
/// # }
/// ```
///
/// To prevent unsoundness, this crate enforces a **runtime check**:
///
/// * Creating a new local reference with a mutable `Env` that is *not* the top
///   frame will cause a panic.
///
/// ### Rule of thumb
///
/// * Keep only one `Env` in scope at a time.
/// * Always shadow outer `env` variables when introducing a new one.
///
/// As long as you follow this pattern, the type system will ensure that local
/// references are only created from the valid top frame.
///
/// ## Troubleshooting `cannot borrow as mutable`
///
/// If a function takes two or more parameters, one of them is `Env`, and
/// another is something returned by a `Env` method (like [`JObject`]), then
/// calls to that function may not compile:
///
/// ```rust,compile_fail
/// # use jni::{jni_sig, jni_str, errors::Result, Env, objects::*};
/// #
/// # fn f(env: &mut Env) -> Result<()> {
/// fn example_function(
///     env: &mut Env,
///     obj: &JObject,
/// ) {
///     // ...
/// }
///
/// example_function(
///     env,
///     // ERROR: cannot borrow `*env` as mutable more than once at a time
///     &env.new_object(
///         jni_str!("com/example/SomeClass"),
///         jni_sig!("()V"),
///         &[],
///     )?,
/// )
/// # ; Ok(())
/// # }
/// ```
///
/// This comes from the compiler needing to borrow `env` as mutable for the call
/// to `new_object`, but also needing to borrow it as mutable for the call to
/// `example_function`.
///
/// In the past we used to recommend here that you could avoid this by
/// reordering the parameters so that `Env` comes last, but in practice this led
/// to very inconsistent APIs where some functions had `Env` first and some had
/// it last, which was confusing.
///
/// Now the recommendation is to just make sure that reference type arguments
/// are derived before the call:
///
/// ```rust,no_run
/// # use jni::{jni_sig, jni_str, errors::Result, Env, objects::JObject};
/// #
/// # fn f(env: &mut Env) -> Result<()> {
/// # fn example_function(
/// #     env: &mut Env,
/// #     obj: &JObject,
/// # ) {
/// #    // ...
/// # }
/// let obj = env.new_object(
///    jni_str!("com/example/SomeClass"),
///    jni_sig!("()V"),
///    &[],
/// )?;
/// example_function(env, &obj)
/// # ; Ok(())
/// # }
/// ```
///
/// Quite often reference type arguments have already been derived in some outer
/// scope and don't involve any JNI method calls so this isn't too bad in
/// practice and it keeps the APIs more consistent / predictable, with `Env`
/// always coming first.
///
/// # Checked and unchecked methods
///
/// Some of the methods come in two versions: checked (e.g. `call_method`) and
/// unchecked (e.g. `call_method_unchecked`). Under the hood, checked methods
/// perform some checks to ensure the validity of provided signatures, names and
/// arguments, and then call the corresponding unchecked method.
///
/// Checked methods are more flexible as they allow passing class names and
/// method/field descriptors as strings and may perform lookups of class objects
/// and method/field ids for you, also performing all the needed precondition
/// checks. However, these lookup operations are expensive, so if you need to
/// call the same method (or access the same field) multiple times, it is
/// [recommended](https://docs.oracle.com/en/java/javase/11/docs/specs/jni/design.html#accessing-fields-and-methods)
/// to cache the instance of the class and the method/field id, e.g.
///   - in loops
///   - when calling the same Java callback repeatedly.
///
/// If you do not cache references to classes and method/field ids, you will
/// *not* benefit from the unchecked methods.
///
/// Calling unchecked methods with invalid arguments and/or invalid class and
/// method descriptors may lead to segmentation fault.
///
/// # Zero-copy `AsRef<JNIStr>` arguments
///
/// The JNI specification for many functions requires that string arguments are
/// passed as NUL terminated, Modified UTF-8 encoded byte arrays.
///
/// Anything that accepts an `AsRef<JNIStr>` can directly accept a `JNIStr`
/// literal like `jni_str!("java/lang/String")` which will be encoded as MUTF-8
/// at compile time.
///
/// See [jni_str!] for more details.
///
/// For non-literal, dynamic strings then you can use [JNIString::new] to encode
/// strings as MUTF-8 at runtime (derefs as [`JNIStr`]).
///
#[derive(Debug)]
pub struct Env<'local> {
    /// A non-null JNIEnv pointer
    pub(crate) raw: *mut sys::JNIEnv,
    /// The current [`jni::AttachGuard`] nesting level, which we assert matches
    /// the top/current nesting level whenever some API will return a new local
    /// reference
    pub(crate) level: usize,
    owns_attachment: bool,
    _lifetime: PhantomData<&'local ()>,
}

impl Drop for Env<'_> {
    fn drop(&mut self) {
        // NOOP - we just implement Drop so that the compiler won't consider
        // Env to be FFI safe.
    }
}

#[cfg(test)]
mod test {
    use crate::Env;
    static_assertions::assert_not_impl_any!(Env: Send);
    static_assertions::assert_not_impl_any!(Env: Sync);
}

impl<'local> Env<'local> {
    /// Returns an `UnsupportedVersion` error if the current JNI version is
    /// lower than the one given.
    ///
    /// Returns `JavaException` if called while there is a pending exception.
    #[allow(unused)]
    fn ensure_version(&self, version: JNIVersion) -> Result<()> {
        if self.version()? < version {
            Err(Error::UnsupportedVersion)
        } else {
            Ok(())
        }
    }

    /// Create a [`Env`] associated with single JNI local reference frame.
    ///
    /// `level` represents the nesting level of the [`AttachGuard`] that owns
    /// this [`Env`]. This can be compared to [JavaVM::thread_attach_guard_level()]
    /// to check that this [`Env`] is associated with the top-most JNI stack frame.
    ///
    /// `owns_attachment` should be true if this [`Env`] is associated with an
    /// attachment that will detach the thread when dropped.
    pub(crate) unsafe fn new(raw: *mut sys::JNIEnv, level: usize, owns_attachment: bool) -> Self {
        let env = Env {
            raw,
            level,
            owns_attachment,
            _lifetime: PhantomData,
        };
        // Assuming that the application doesn't break the safety rules for
        // keeping the `AttachGuard` on the stack, and not re-ordering them,
        // we can assert that we only ever create an `Env` for the top-most
        // guard on the stack.
        env.assert_top();
        env
    }

    /// Runtime check that this [`Env`] represents the top JNI stack frame
    ///
    /// Any lower-level API that returns a new local reference must call this
    /// method to ensure the reference is tied to the correct JNI stack frame.
    ///
    /// All safe APIs that return a new local reference already call this but you
    /// may need to call this in `unsafe` code that uses [`crate::sys`] functions
    /// directly.
    ///
    /// See the safety documentation for [`AttachGuard`] for more details.
    #[inline]
    pub fn assert_top(&self) {
        // Runtime check that the 'local reference lifetime will be tied to
        // Env lifetime for the top JNI stack frame
        assert_eq!(
            self.level,
            JavaVM::thread_attach_guard_level(),
            r#" jni runtime check failure: attempt to create a new local reference using an Env<'not_top> that is not associated with the top JNI stack frame.

This implies that there is more than one mutable Env in scope.

This should only be possible by misusing APIs like JavaVM::attach_current_thread or Env::with_local_frame to materialize a mutable Env when there is already one in scope.

To fix this, ensure that you only ever have one mutable Env in scope at a time, which is associated with the top JNI stack frame.

See the jni-rs Env documentation for more details.
"#
        );
    }

    /// Returns true if this [`Env`] is associated with a scoped attachment that
    /// will also detach the thread when it is dropped.
    ///
    /// An owned attachment would come from a call to
    /// [`JavaVM::attach_current_thread_for_scope`] but only if the thread was
    /// not already attached.
    ///
    /// This can be used to recognise when
    /// [`JavaVM::attach_current_thread_for_scope`] really needed to attach the
    /// thread, or if the thread was already attached.
    ///
    /// This is mostly useful for diagnostic purposes. For example the `Drop`
    /// implementation for [`Global`] and [`Weak`] will print a warning if they
    /// are dropped on a thread that is not attached, which is recognised with
    /// this method.
    pub fn owns_attachment(&self) -> bool {
        self.owns_attachment
    }

    /// Get the raw Env pointer
    pub fn get_raw(&self) -> *mut sys::JNIEnv {
        self.raw
    }

    /// Get the JNI version that this [`Env`] supports.
    ///
    /// This can return an error if called while there is a pending JNI exception
    pub fn version(&self) -> Result<JNIVersion> {
        // Safety: GetVersion is 1.1 API that must be valid
        Ok(JNIVersion::from(unsafe {
            jni_call_no_post_check_ex!(self, v1_1, GetVersion)?
        }))
    }

    #[doc(hidden)]
    #[deprecated(since = "0.22.0", note = "Renamed to `version` instead")]
    pub fn get_version(&self) -> Result<JNIVersion> {
        self.version()
    }

    /// Load a class from a buffer of raw class data.
    ///
    /// If `name` is null, the name of the class is inferred from the buffer.
    ///
    /// Note: This requires `&mut` because it returns a new local reference to a class.
    ///
    /// # Safety
    ///
    /// The `buf` pointer must be valid for `buf_len` bytes.
    unsafe fn define_class_impl(
        &mut self,
        name: *const c_char,
        loader: &JClassLoader,
        buf: *const jbyte,
        buf_len: usize,
    ) -> Result<JClass<'local>> {
        if buf_len > jsize::MAX as usize {
            return Err(Error::JniCall(JniError::InvalidArguments));
        }
        // Runtime check that the 'local reference lifetime will be tied to
        // Env lifetime for the top JNI stack frame
        self.assert_top();
        // Safety:
        // - DefineClass is 1.1 API that must be valid
        // - It is valid to potentially pass a `null` `name` to `DefineClass`, since the name can be
        // read from the bytecode.
        // - A null loader corresponds to the bootstrap class loader.
        //
        // Throws:
        // - `ClassFormatError`: if the class data does not specify a valid class.
        // - `ClassCircularityError`: if a class or interface would be its own superclass or
        //   superinterface.
        // - `OutOfMemoryError`: if the system runs out of memory.
        // - `SecurityException`: if the caller attempts to define a class in the `"java"` package
        //   tree.
        unsafe {
            jni_call_with_catch_and_null_check!(
                catch |env| {
                    crate::exceptions::JClassFormatError =>
                        Err(Error::ClassFormatError),
                    crate::exceptions::JClassCircularityError =>
                        Err(Error::ClassCircularityError),
                    crate::exceptions::JOutOfMemoryError =>
                        Err(Error::JniCall(JniError::NoMemory)),
                    crate::exceptions::JSecurityException =>
                        Err(Error::SecurityViolation),
                    else => Err(Error::NullPtr("Unexpected Exception")),
                },
                self,
                v1_1,
                DefineClass,
                name,
                loader.as_raw(),
                buf,
                buf_len as jsize
            )
            .map(|class| JClass::from_raw(self, class))
        }
    }

    /// Load a class from a buffer of raw class data.
    ///
    /// If `name` is `None` then the name of the loaded class will be inferred, otherwise the given
    /// `name` must match the name encoded within the class file data.
    ///
    /// Typically the `loader` should come from [`JClassLoader::get_system_class_loader`] or the
    /// loader from some other application-specific class.
    ///
    /// If `loader` is `null` then the bootstrap class loader will be used, which may not be able to
    /// load dependencies of the defined class.
    ///
    /// Alternatively, call [`Self::define_class_jbyte`] if your data comes from a [`JByteArray`] or
    /// `&[jbyte]`.
    ///
    /// - Returns [`Error::ClassFormatError`] if the class data does not specify a valid class.
    /// - Returns [`Error::ClassCircularityError`] if a class or interface would be its own
    ///   superclass or superinterface.
    /// - Returns [`Error::JniCall`] + [`JniError::NoMemory`] if the JVM reports running out of
    ///   memory.
    /// - Returns [`Error::SecurityViolation`] if the caller attempts to define a class in the
    ///   `"java"` package tree.
    ///
    /// This API catches exceptions internally and is not expected to return
    /// [`Error::JavaException`] (unless called while there is a pending exception).
    ///
    /// # Portability Note
    ///
    /// The JNI `DefineClass` function may not be supported by all JVM implementations, even though
    /// it is part of the JNI specification.
    ///
    /// In particular Android's ART runtime does not support it, since all classes must be
    /// pre-compiled into DEX format.
    pub fn define_class<'any_loader, N, L>(
        &mut self,
        name: Option<N>,
        loader: L,
        buf: &[u8],
    ) -> Result<JClass<'local>>
    where
        N: AsRef<JNIStr>,
        L: AsRef<JClassLoader<'any_loader>>,
    {
        let name: Option<&JNIStr> = name.as_ref().map(|n| n.as_ref());
        let name = name.map_or(ptr::null(), |n| n.as_ptr());
        // Safety: we know the pointer for the u8 slice is valid for buf.len() bytes
        unsafe {
            self.define_class_impl(
                name,
                loader.as_ref(),
                buf.as_ptr() as *const jbyte,
                buf.len(),
            )
        }
    }

    /// Load a class from a buffer of raw class data.
    ///
    /// If `name` is `None` then the name of the loaded class will be inferred, otherwise the given
    /// `name` must match the name encoded within the class file data.
    ///
    /// Typically the `loader` should come from [`JClassLoader::get_system_class_loader`] or the
    /// loader from some other application-specific class.
    ///
    /// If `loader` is `null` then the bootstrap class loader will be used, which may not be able to
    /// load dependencies of the defined class.
    ///
    /// This is the same as [`Self::define_class`] but takes a `&[jbyte]` instead of `&[u8]`.
    ///
    /// - Returns [`Error::ClassFormatError`] if the class data does not specify a valid class.
    /// - Returns [`Error::ClassCircularityError`] if a class or interface would be its own
    ///   superclass or superinterface.
    /// - Returns [`Error::JniCall`] + [`JniError::NoMemory`] if the JVM reports running out of
    ///   memory.
    /// - Returns [`Error::SecurityViolation`] if the caller attempts to define a class in the
    ///   `"java"` package tree.
    ///
    /// This API catches exceptions internally and is not expected to return
    /// [`Error::JavaException`] (unless called while there is a pending exception).
    ///
    /// # Portability Note
    ///
    /// The JNI `DefineClass` function may not be supported by all JVM implementations, even though
    /// it is part of the JNI specification.
    ///
    /// In particular Android's ART runtime does not support it, since all classes must be
    /// pre-compiled into DEX format.
    pub fn define_class_jbyte<'any_loader, N, L>(
        &mut self,
        name: Option<N>,
        loader: L,
        buf: &[jbyte],
    ) -> Result<JClass<'local>>
    where
        N: AsRef<JNIStr>,
        L: AsRef<JClassLoader<'any_loader>>,
    {
        let name: Option<&JNIStr> = name.as_ref().map(|n| n.as_ref());
        let name = name.as_ref().map_or(ptr::null(), |n| n.as_ptr());
        // Safety: we know the pointer for the u8 slice is valid for buf.len() bytes
        unsafe {
            self.define_class_impl(
                name,
                loader.as_ref(),
                buf.as_ptr() as *const jbyte,
                buf.len(),
            )
        }
    }

    /// Look up a class by its fully-qualified "internal" JNI name, via JNI
    /// `FindClass`.
    ///
    /// **Note:** Only use this method if you _strictly_ need the JNI
    /// `FindClass` behavior exactly, otherwise, it is strongly recommended to
    /// use [Reference::lookup_class] (cached), [Env::load_class] or
    /// [LoaderContext::load_class].
    ///
    /// The `name` must be in the "internal" form, with slashes instead of dots,
    /// like `jni_str!("java/lang/IllegalArgumentException")` or an array
    /// descriptor like `jni_str!("[Ljava/lang/Number;")`.
    ///
    /// # Example
    /// ```rust,no_run
    /// # use jni::{jni_str, errors::Result, Env, objects::JClass};
    /// #
    /// # fn example<'local>(env: &mut Env<'local>) -> Result<()> {
    /// let class: JClass<'local> = env.find_class(jni_str!("java/lang/IllegalArgumentException"))?;
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// - Returns a reference to loaded class on success
    /// - Returns [`Error::NoClassDefFound`] if a `NoClassDefFoundError`
    ///   exception occurs, indicating that no definition for a requested class
    ///   or interface can be found (most common failure)
    /// - Returns [`Error::ClassFormatError`] if a `ClassFormatError` exception
    ///   occurs, indicating that the class data does not specify a valid class.
    /// - Returns [`Error::ClassCircularityError`] if a `ClassCircularityError`
    ///   exception occurs, indicating that a class or interface would be its
    ///   own superclass or superinterface.
    /// - Returns [`Error::JniCall`] + [`JniError::NoMemory`] if an
    ///   `OutOfMemoryError` exception occurs, indicating that the JVM reports
    ///   running out of memory.
    /// - Returns [`Error::NullPtr`] for any other unknown error condition
    ///
    /// This API catches exceptions internally and is not expected to return
    /// [`Error::JavaException`] (unless called while there is a pending
    /// exception).
    ///
    /// # Android
    ///
    /// On Android in particular it's notable that `FindClass` will not be able
    /// to find application classes when called from a native thread, outside of
    /// a native method call.
    ///
    /// [Env::load_class] can work on Android if a loader has been set up for
    /// the current thread (see: [JThread::set_context_class_loader]) and if you
    /// use the `android-activity` crate this may be done for you.
    pub fn find_class<S>(&mut self, name: S) -> Result<JClass<'local>>
    where
        S: AsRef<JNIStr>,
    {
        // Runtime check that the 'local reference lifetime will be tied to
        // Env lifetime for the top JNI stack frame
        self.assert_top();
        let name = name.as_ref();
        // Safety:
        // FindClass is 1.1 API that must be valid
        // name is non-null
        unsafe {
            jni_call_with_catch_and_null_check!(
                catch |env| {
                    e: crate::exceptions::JNoClassDefFoundError => {
                        let cause: &JThrowable = &e.as_throwable();
                        let cause = env.new_global_ref(cause).ok();
                        Err(Error::NoClassDefFound {
                            requested: name.to_string(),
                            cause
                        })
                    },
                    // Although the JNI spec does not list `ClassNotFoundException` as a possible
                    // exception for `FindClass` we want to make sure that would be mapped to
                    // Error:NoClassDefFound, consistent with `LoaderContext::load_class`
                    e: crate::exceptions::JClassNotFoundException => {
                        let cause: &JThrowable = &e.as_throwable();
                        let cause = env.new_global_ref(cause).ok();
                        Err(Error::NoClassDefFound {
                            requested: name.to_string(),
                            cause
                        })
                    },
                    crate::exceptions::JClassFormatError =>
                        Err(Error::ClassFormatError),
                    crate::exceptions::JClassCircularityError =>
                        Err(Error::ClassCircularityError),

                    // Although the JNI spec doesn't say that `FindClass` may throw `LinkageErrors`,
                    // we want to make sure we would map them to `Error::LinkageError`, consistent
                    // with `LoaderContext::load_class`
                    e: crate::exceptions::JLinkageError => {
                        let cause: &JThrowable = &e.as_throwable();
                        let cause = env.new_global_ref(cause).ok();
                        Err(Error::LinkageError {
                            requested: name.to_string(),
                            cause
                        })
                    },
                    crate::exceptions::JOutOfMemoryError =>
                        Err(Error::JniCall(JniError::NoMemory)),
                    else => Err(Error::NullPtr("Unexpected exception")),
                },
                self, v1_1, FindClass, name.as_ptr())
            .map(|class| JClass::from_raw(self, class))
        }
    }

    /// Look up a class by its fully-qualified name, via `Class.forName(<name>,
    /// <initialize>, <loader>)` with a `FindClass` fallback.
    ///
    /// This is a convenience wrapper around [LoaderContext::load_class] with
    /// [LoaderContext::None].
    ///
    /// `name` should be a binary name like `jni_str!("java.lang.Number")` or an
    /// array descriptor like `jni_str!("[Ljava.lang.Number;")`.
    ///
    /// **Note:** that unlike [Env::find_class], the name uses **dots instead of
    /// slashes** and should conform to the format that `Class.getName()`
    /// returns and that `Class.forName()` expects.
    ///
    /// For example, lookup the class for
    /// `java.lang.IllegalArgumentException`like this:
    /// ```rust,no_run
    /// # use jni::{jni_str, errors::Result, Env, objects::JClass};
    /// #
    /// # fn example<'local>(env: &mut Env<'local>) -> Result<()> {
    /// let class: JClass<'local> = env.load_class(jni_str!("java.lang.IllegalArgumentException"))?;
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// - Returns a reference to loaded class on success
    /// - Returns [`Error::NoClassDefFound`] if a `NoClassDefFoundError` or
    ///   `ClassNotFoundException` exception occurs, indicating that no
    ///   definition for a requested class or interface can be found (most
    ///   common failure)
    /// - Returns [`Error::ClassFormatError`] if a `ClassFormatError` exception
    ///   occurs, indicating that the class data does not specify a valid class.
    /// - Returns [`Error::ClassCircularityError`] if a `ClassCircularityError`
    ///   exception occurs, indicating that a class or interface would be its
    ///   own superclass or superinterface.
    /// - May Return [`Error::LinkageError`] for various failures to link the
    ///   requested class.
    /// - May Return [`Error::ExceptionInInitializer`] if an exception occurs
    ///   during class initialization.
    /// - Returns [`Error::JniCall`] + [`JniError::NoMemory`] if an
    ///   `OutOfMemoryError` exception occurs, indicating that the JVM reports
    ///   running out of memory.
    /// - Returns [`Error::NullPtr`] for any other unknown error condition
    ///
    /// *Note:* In order for this API to be consistent with
    /// [`jni::Env::find_class`], this API does _not_ directly return
    /// [`Error::ClassNotFound`] errors that may come directly from the loader.
    ///
    /// *Note:* Any [`Error::NoClassDefFound`], [`Error::LinkageError`] or
    /// [`Error::ExceptionInInitializer`] errors include the original `cause`
    /// exception if more details are needed.
    ///
    /// # Android
    ///
    /// This API will notably check the context class loader of the current
    /// thread, which makes it possible to associate a thread with an
    /// application class loader.
    ///
    /// This may be particularly useful for native applications on Android
    /// because native threads will not normally be able to find application
    /// classes through `FindClass`.
    ///
    /// If you use the `android-activity` crate, it may set up the context class
    /// loader for you.
    pub fn load_class<S>(&mut self, name: S) -> Result<JClass<'local>>
    where
        S: AsRef<JNIStr>,
    {
        let name = name.as_ref();
        LoaderContext::None.load_class(self, name, false)
    }

    /// Returns the superclass for a particular class. Returns None for `java.lang.Object` or
    /// an interface. As with [Self::find_class], takes a descriptor
    ///
    /// # Errors
    ///
    /// If a JNI call fails
    pub fn get_superclass<'other_local, T>(&mut self, class: T) -> Result<Option<JClass<'local>>>
    where
        T: Desc<'local, JClass<'other_local>>,
    {
        // Runtime check that the 'local reference lifetime will be tied to
        // Env lifetime for the top JNI stack frame
        self.assert_top();
        let class = class.lookup(self)?;
        let superclass = unsafe {
            JClass::from_raw(
                self,
                jni_call_no_post_check_ex!(self, v1_1, GetSuperclass, class.as_ref().as_raw())?,
            )
        };

        Ok((!superclass.is_null()).then_some(superclass))
    }

    // Like is_assignable_from but it doesn't need a mutable Env reference because it doesn't do any
    // descriptor lookups.
    fn is_assignable_from_class(&self, class1: &JClass, class2: &JClass) -> Result<bool> {
        let class1 = null_check!(class1, "is_assignable_from class1")?;
        let class2 = null_check!(class2, "is_assignable_from class2")?;

        // Safety:
        // - IsAssignableFrom is 1.1 API that must be valid
        // - We make sure class1 and class2 can't be null
        unsafe {
            Ok(jni_call_no_post_check_ex!(
                self,
                v1_1,
                IsAssignableFrom,
                class1.as_raw(), // MUST not be null
                class2.as_raw()  // MUST not be null
            )?)
        }
    }

    // FIXME: this API shouldn't need a `&mut self` reference since it doesn't return a local reference
    // (currently it just needs the `&mut self` for the sake of `Desc<JClass>::lookup`)
    //
    /// Tests whether class1 is assignable from class2.
    pub fn is_assignable_from<'other_local_1, 'other_local_2, T, U>(
        &mut self,
        class1: T,
        class2: U,
    ) -> Result<bool>
    where
        T: Desc<'local, JClass<'other_local_1>>,
        U: Desc<'local, JClass<'other_local_2>>,
    {
        let class1 = class1.lookup(self)?;
        let class1 = null_check!(class1.as_ref(), "is_assignable_from class1")?;
        let class2 = class2.lookup(self)?;
        let class2 = null_check!(class2.as_ref(), "is_assignable_from class2")?;

        self.is_assignable_from_class(class1, class2)
    }

    /// Checks if an object can be cast to a specific reference type.
    pub(crate) fn is_instance_of_cast_type<To: Reference>(&self, obj: &JObject) -> Result<bool> {
        let class = match To::lookup_class(self, &LoaderContext::FromObject(obj)) {
            Ok(class) => class,
            Err(Error::ClassNotFound { name: _ }) => return Ok(false),
            Err(e) => return Err(e),
        };

        let class: &JClass = &class;
        self.is_instance_of_class(obj, class)
    }

    // An internal helper that implements is_instance_of except it doesn't take a
    // Desc for the class and doesn't need a mutable Env reference since it never
    // needs to allocate a new local reference.
    /// Returns true if the object reference can be cast to the given type.
    pub(crate) fn is_instance_of_class<'other_local_1, 'other_local_2, O, C>(
        &self,
        object: O,
        class: C,
    ) -> Result<bool>
    where
        O: AsRef<JObject<'other_local_1>>,
        C: AsRef<JClass<'other_local_2>>,
    {
        let class = null_check!(class.as_ref(), "is_instance_of class")?;

        // Safety:
        // - IsInstanceOf is 1.1 API that must be valid
        // - We make sure class can't be null
        unsafe {
            Ok(jni_call_no_post_check_ex!(
                self,
                v1_1,
                IsInstanceOf,
                object.as_ref().as_raw(), // may be null
                class.as_raw()            // MUST not be null
            )?)
        }
    }

    // FIXME: this API shouldn't need a `&mut self` reference since it doesn't return a local reference
    // (currently it just needs the `&mut self` for the sake of `Desc<JClass>::lookup`)
    //
    /// Returns true if the object reference can be cast to the given type.
    ///
    /// _NB: Unlike the operator `instanceof`, function `IsInstanceOf` *returns `true`*
    /// for all classes *if `object` is `null`.*_
    ///
    /// See [JNI documentation](https://docs.oracle.com/javase/8/docs/technotes/guides/jni/spec/functions.html#IsInstanceOf)
    /// for details.
    pub fn is_instance_of<'other_local_1, 'other_local_2, O, T>(
        &mut self,
        object: O,
        class: T,
    ) -> Result<bool>
    where
        O: AsRef<JObject<'other_local_1>>,
        T: Desc<'local, JClass<'other_local_2>>,
    {
        let class = class.lookup(self)?;
        self.is_instance_of_class(object, class)
    }

    /// Returns true if ref1 and ref2 refer to the same Java object, or are both `NULL`. Otherwise,
    /// returns false.
    ///
    /// Returns [`Error::JavaException`] if called while there is a pending Java exception
    pub fn is_same_object<'other_local_1, 'other_local_2, O, T>(
        &self,
        ref1: O,
        ref2: T,
    ) -> Result<bool>
    where
        O: AsRef<JObject<'other_local_1>>,
        T: AsRef<JObject<'other_local_2>>,
    {
        // Safety:
        // - IsSameObject is 1.1 API that must be valid
        // - the spec allows either object reference to be `null`
        unsafe {
            jni_call_no_post_check_ex!(
                self,
                v1_1,
                IsSameObject,
                ref1.as_ref().as_raw(), // may be null
                ref2.as_ref().as_raw()  // may be null
            )
        }
    }

    // FIXME: this API shouldn't need a `&mut self` reference since it doesn't return a local reference
    // (currently it just needs the `&mut self` for the sake of `Desc<JThrowable>::lookup`)
    //
    /// Raise an exception from an existing object. This will continue being thrown in java unless
    /// `exception_clear` is called.
    ///
    /// Returns [`Error::JavaException`] after throwing the exception.
    ///
    /// The '?' operator should typically used to ensure that the new pending exception is reported
    /// as an error to calling Rust code, allowing the stack to unwind until something decides to
    /// catch the exception (or it propagates back to the JVM).
    ///
    /// *Note:* that once there is a pending exception then most JNI calls (that are not exception
    /// safe) will return [`Error::JavaException`] until the exception is cleared.
    ///
    /// # Examples
    /// ```rust,no_run
    /// # use jni::{jni_str, errors::Result, Env};
    /// #
    /// # fn example(env: &mut Env) -> Result<()> {
    /// env.throw((jni_str!("java/lang/Exception"), jni_str!("something bad happened")))?;
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// Defaulting to "java/lang/Exception":
    ///
    /// ```rust,no_run
    /// # use jni::{jni_str, errors::Result, Env};
    /// #
    /// # fn example(env: &mut Env) -> Result<()> {
    /// env.throw(jni_str!("something bad happened"))?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn throw<'other_local, E>(&mut self, obj: E) -> Result<()>
    where
        E: Desc<'local, JThrowable<'other_local>>,
    {
        let throwable = obj.lookup(self)?;

        // Safety:
        // Throw is 1.1 API that must be valid
        //
        // We are careful to ensure that we don't drop the reference
        // to `throwable` after converting to a raw pointer.
        let res: i32 =
            unsafe { jni_call_no_post_check_ex!(self, v1_1, Throw, throwable.as_ref().as_raw())? };

        // Ensure that `throwable` isn't dropped before the JNI call returns.
        drop(throwable);

        if res == 0 {
            Err(Error::JavaException)
        } else {
            Err(Error::ThrowFailed(res))
        }
    }

    // FIXME: this API shouldn't need a `&mut self` reference since it doesn't return a local reference
    // (currently it just needs the `&mut self` for the sake of `Desc<JClass>::lookup`)
    fn throw_new_optional(&self, class: &JClass, msg: Option<&JNIStr>) -> Result<()> {
        let throwable_class = JThrowable::lookup_class(self, &LoaderContext::None)?;
        let throwable_class: &JClass = &throwable_class;

        if !self.is_assignable_from_class(class.as_ref(), throwable_class)? {
            return Err(Error::WrongObjectType);
        }
        let msg = msg.as_ref().map(|m| m.as_ref());

        // Safety:
        // ThrowNew is 1.1 API that must be valid
        //
        // We are careful to ensure that we don't drop the reference
        // to `class` or `msg` after converting to raw pointers.
        let res: i32 = unsafe {
            jni_call_no_post_check_ex!(
                self,
                v1_1,
                ThrowNew,
                class.as_raw(),
                msg.map(|m| m.as_ptr()).unwrap_or(std::ptr::null())
            )?
        };

        if res == 0 {
            Err(Error::JavaException)
        } else {
            Err(Error::ThrowFailed(res))
        }
    }

    // FIXME: this API shouldn't need a `&mut self` reference since it doesn't return a local reference
    // (currently it just needs the `&mut self` for the sake of `Desc<JClass>::lookup`)
    //
    /// Create and throw a new exception from a class descriptor and an error message.
    ///
    /// The '?' operator should typically used to ensure that the new pending exception is reported
    /// as an error to calling Rust code, allowing the stack to unwind until something decides to
    /// catch the exception (or it propagates back to the JVM).
    ///
    /// *Note:* that once there is a pending exception then most JNI calls (that are not exception
    /// safe) will return [`Error::JavaException`] until the exception is cleared.
    ///
    /// # Example
    /// ```rust,no_run
    /// # use jni::{jni_str, errors::Result, Env};
    /// #
    /// # fn example(env: &mut Env) -> Result<()> {
    /// env.throw_new(jni_str!("java/lang/Exception"), jni_str!("something bad happened"))?;
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// Alternatively, see [Env::throw_new_void] if you want to construct an exception with no
    /// message argument.
    pub fn throw_new<'other_local, S, T>(&mut self, class: T, msg: S) -> Result<()>
    where
        S: AsRef<JNIStr>,
        T: Desc<'local, JClass<'other_local>>,
    {
        let class = class.lookup(self)?;
        let msg: &JNIStr = msg.as_ref();
        self.throw_new_optional(class.as_ref(), Some(msg))
    }

    /// Create and throw a new exception from a class descriptor and no error message.
    ///
    /// The '?' operator should typically used to ensure that the new pending exception is reported
    /// as an error to calling Rust code, allowing the stack to unwind until something decides to
    /// catch the exception (or it propagates back to the JVM).
    ///
    /// *Note:* that once there is a pending exception then most JNI calls (that are not exception
    /// safe) will return [`Error::JavaException`] until the exception is cleared.
    ///
    /// # Example
    /// ```rust,no_run
    /// # use jni::{jni_str, errors::Result, Env};
    /// #
    /// # fn example(env: &mut Env) -> Result<()> {
    /// env.throw_new_void(jni_str!("java/lang/Exception"))?;
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// This will expect to find a constructor for the given `class` that takes no arguments.
    ///
    /// Alternatively, see [Env::throw_new] if you want to construct an exception with a message.
    pub fn throw_new_void<'other_local, T>(&mut self, class: T) -> Result<()>
    where
        T: Desc<'local, JClass<'other_local>>,
    {
        let class = class.lookup(self)?;
        self.throw_new_optional(class.as_ref(), None)
    }

    /// Returns true if an exception is currently in the process of being thrown.
    ///
    /// This doesn't need to create any local references
    #[inline]
    pub fn exception_check(&self) -> bool {
        // Safety: ExceptionCheck is 1.2 API, which we check for in `from_raw()`
        unsafe { ex_safe_jni_call_no_post_check_ex!(self, v1_2, ExceptionCheck) }
    }

    /// Check whether or not an exception is currently in the process of being
    /// thrown.
    ///
    /// An exception is in this state from the time it gets thrown and
    /// not caught in a java function until `exception_clear` is called.
    pub fn exception_occurred(&mut self) -> Option<JThrowable<'local>> {
        // Runtime check that the 'local reference lifetime will be tied to
        // Env lifetime for the top JNI stack frame
        self.assert_top();
        let throwable =
            unsafe { ex_safe_jni_call_no_post_check_ex!(self, v1_1, ExceptionOccurred) };
        if throwable.is_null() {
            None
        } else {
            Some(unsafe { JThrowable::from_raw(self, throwable) })
        }
    }

    /// Print exception information to the console.
    pub fn exception_describe(&self) {
        // Safety: ExceptionDescribe is 1.1 API that must be valid
        unsafe { ex_safe_jni_call_no_post_check_ex!(self, v1_1, ExceptionDescribe) };
    }

    /// Clear an exception in the process of being thrown. If this is never
    /// called, the exception will continue being thrown when control is
    /// returned to java.
    pub fn exception_clear(&self) {
        // Safety: ExceptionClear is 1.1 API that must be valid
        unsafe { ex_safe_jni_call_no_post_check_ex!(self, v1_1, ExceptionClear) };
    }

    /// Catch a pending Java exception and convert it into a Rust
    /// [`Error::CaughtJavaException`].
    ///
    /// If a Java exception is pending, it will be cleared and converted into a
    /// Rust [`Error::CaughtJavaException`].
    pub fn exception_catch(&self) -> Result<()> {
        fn try_get_stack_trace(
            env: &mut jni::Env<'_>,
            throwable: &jni::objects::JThrowable,
        ) -> jni::errors::Result<String> {
            let stack_trace = throwable.get_stack_trace(env)?;
            let len = stack_trace.len(env)?;
            let mut trace = String::new();
            for i in 0..len {
                let element = stack_trace.get_element(env, i)?;
                let element_jstr = element.try_to_string(env)?;
                trace.push_str(&format!("{i}: {element_jstr}\n"));
            }
            Ok(trace)
        }

        if self.exception_check() {
            let result = self.with_local_frame(
                DEFAULT_LOCAL_FRAME_CAPACITY,
                |env| -> jni::errors::Result<jni::errors::Error> {
                    let Some(e) = env.exception_occurred() else {
                        // should only be called after receiving a JavaException Result
                        unreachable!(
                            "ExceptionOccurred returned None after ExceptionCheck returned true"
                        );
                    };
                    env.exception_clear();

                    assert!(!e.is_null(), "ExceptionOccurred returned a null throwable");

                    let e = env.new_global_ref(e)?;
                    // besides null pointer checks, there are no documented errors or exceptions
                    // for GetObjectClass or getName, so this should be infallible
                    let name = env.get_object_class(&e)?.get_name(env)?.to_string();
                    let msg = e.get_message(env)?.to_string();

                    let stack = match try_get_stack_trace(env, &e) {
                        Ok(stack_trace) => stack_trace,
                        Err(err) => format!("none: {err:?}"),
                    };

                    Ok(jni::errors::Error::CaughtJavaException {
                        exception: e,
                        name,
                        msg,
                        stack,
                    })
                },
            );

            match result {
                Ok(exception) => Err(exception),
                Err(err) => Err(jni::errors::Error::CaughtJavaException {
                    exception: Default::default(),
                    name: "UNKNOWN".to_string(),
                    msg: format!("Failed to query JThrowable: {err:?})"),
                    stack: "none".to_string(),
                }),
            }
        } else {
            Ok(())
        }
    }

    /// Abort the JVM with an error message.
    ///
    /// This method is guaranteed not to panic, and only calls `ExceptionClear`
    /// prior to calling [`FatalError`]. The `jni-rs` wrapper function does not
    /// perform any heap allocations (although `FatalError` might perform heap
    /// allocations of its own).
    ///
    /// In exchange for these strong guarantees, this method requires an error
    /// message to already be suitably encoded, as described in the
    /// documentation for the [`JNIStr`] type.
    ///
    /// The simplest way to use this is to convert a string to a [`JNIStr`] via
    /// [`jni::jni_str!`] like so:
    ///
    /// ```no_run
    /// # use jni::{jni_str, Env, strings::JNIStr};
    /// # let env: Env = unimplemented!();
    /// env.fatal_error(jni_str!("Game over!"))
    /// ```
    ///
    /// [`FatalError`]:
    ///     https://docs.oracle.com/en/java/javase/21/docs/specs/jni/functions.html#fatalerror
    /// [`ExceptionClear`]:
    ///     https://docs.oracle.com/en/java/javase/21/docs/specs/jni/functions.html#exceptionclear
    /// [Modified UTF-8]:
    ///     https://docs.oracle.com/en/java/javase/21/docs/specs/jni/types.html#modified-utf-8-strings
    pub fn fatal_error(&self, msg: &JNIStr) -> ! {
        // Since FatalError is not considered to safe to call with a pending exception
        // we have to first clear any pending exception.
        self.exception_clear();

        // Safety: FatalError is 1.1 API that must be valid
        //
        // Very little is specified about the implementation of FatalError but we still
        // currently consider this "safe", similar to how `abort()` is considered safe.
        // It won't give the application an opportunity to clean or save state but the
        // process will be terminated.
        //
        // Although FatalError is not exception safe, we call it as if it is because
        // we have guaranteed that there are no pending exceptions to check for.
        unsafe { ex_safe_jni_call_no_post_check_ex!(self, v1_1, FatalError, msg.as_ptr()) }
    }

    /// Create a new instance of a direct java.nio.ByteBuffer
    ///
    /// # Example
    /// ```rust,no_run
    /// # use jni::{errors::Result, Env};
    /// #
    /// # fn example(env: &mut Env) -> Result<()> {
    /// let buf = vec![0; 1024 * 1024];
    /// let (addr, len) = { // (use buf.into_raw_parts() on nightly)
    ///     let buf = buf.leak();
    ///     (buf.as_mut_ptr(), buf.len())
    /// };
    /// let direct_buffer = unsafe { env.new_direct_byte_buffer(addr, len) }?;
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # Safety
    ///
    /// Expects a valid (non-null) pointer and length
    ///
    /// Caller must ensure the lifetime of `data` extends to all uses of the returned
    /// `ByteBuffer`. The JVM may maintain references to the `ByteBuffer` beyond the lifetime
    /// of this `Env`.
    pub unsafe fn new_direct_byte_buffer(
        &mut self,
        data: *mut u8,
        len: usize,
    ) -> Result<JByteBuffer<'local>> {
        // Runtime check that the 'local reference lifetime will be tied to
        // Env lifetime for the top JNI stack frame
        self.assert_top();
        let data = null_check!(data, "new_direct_byte_buffer data argument")?;
        // Safety: jni-rs requires JNI >= 1.4
        unsafe {
            let obj = jni_call_with_catch_and_null_check!(
                catch |env| {
                    crate::exceptions::JIllegalArgumentException =>
                        Err(Error::JniCall(JniError::InvalidArguments)),
                    crate::exceptions::JOutOfMemoryError =>
                        Err(Error::JniCall(JniError::NoMemory)),
                    else => Err(Error::NullPtr("Unexpected Exception")),
                },
                self,
                v1_4,
                NewDirectByteBuffer,
                data as *mut c_void,
                len as jlong
            )?;
            Ok(JByteBuffer::from_raw(self, obj))
        }
    }

    /// Returns the starting address of the memory of the direct
    /// java.nio.ByteBuffer.
    ///
    /// # Safety
    ///
    /// The caller must ensure the lifetime of `buf` extends to all uses of the
    /// returned pointer.
    pub fn get_direct_buffer_address(&self, buf: &JByteBuffer) -> Result<*mut u8> {
        let buf = null_check!(buf, "get_direct_buffer_address argument")?;
        // Safety: jni-rs requires JNI >= 1.4 and this is checked in `from_raw`
        unsafe {
            // GetDirectBufferAddress has no documented exceptions that it can throw
            let ptr =
                jni_call_only_check_null_ret!(self, v1_4, GetDirectBufferAddress, buf.as_raw())?;
            Ok(ptr as _)
        }
    }

    /// Returns the capacity (length) of the direct java.nio.ByteBuffer.
    ///
    /// # Terminology
    ///
    /// "capacity" here means the length that was passed to [`Self::new_direct_byte_buffer()`]
    /// which does not reflect the (potentially) larger size of the underlying allocation (unlike the `Vec`
    /// API).
    ///
    /// The terminology is simply kept from the original JNI API (`GetDirectBufferCapacity`).
    pub fn get_direct_buffer_capacity(&self, buf: &JByteBuffer) -> Result<usize> {
        let buf = null_check!(buf, "get_direct_buffer_capacity argument")?;
        // Safety: jni-rs requires JNI >= 1.4 and this is checked in `from_raw`
        unsafe {
            let capacity =
                jni_call_no_post_check_ex!(self, v1_4, GetDirectBufferCapacity, buf.as_raw())?;
            match capacity {
                -1 => Err(Error::JniCall(JniError::Unknown)),
                _ => Ok(capacity as usize),
            }
        }
    }

    /// Creates a new global reference to the Java object `obj`.
    ///
    /// Global references take more time to create or delete than ordinary
    /// local references do, but have several properties that make them useful
    /// in certain situations. See [`Global`] for more information.
    ///
    /// If you use this API to try and upgrade a [`Weak`] then it may return
    /// [`Error::ObjectFreed`] if the object has been garbage collected.
    pub fn new_global_ref<'any_local, O>(&self, obj: O) -> Result<Global<O::GlobalKind>>
    where
        O: Reference + AsRef<JObject<'any_local>>,
    {
        // Avoid passing null to `NewGlobalRef` so that we can recognise out-of-memory errors
        if obj.is_null() {
            return Ok(Global::null());
        }

        // Safety:
        // - the minimum supported JNI version is 1.4
        // - we can assume that `obj.raw()` is a valid reference
        // - we know there's no other wrapper for the reference passed to from_global_raw
        //   since we have just created it.
        let global_ref = unsafe {
            let global_ref = O::global_kind_from_raw(jni_call_no_post_check_ex!(
                self,
                v1_1,
                NewGlobalRef,
                obj.as_raw()
            )?);
            Global::new(self, global_ref)
        };

        // Per JNI spec, `NewGlobalRef` will return a null pointer if the object was GC'd
        // (which could happen if `obj` is a `Weak`):
        //
        //  > it is recommended that a (strong) local or global reference to the
        //  > underlying object be acquired using one of the JNI functions
        //  > NewLocalRef or NewGlobalRef. These functions will return NULL if
        //  > the object has been freed.
        //
        if global_ref.is_null() {
            // In this case it's ambiguous whether there has been an out-of-memory error or
            // the object has been garbage collected and so we now _explicitly_ check
            // whether the object has been garbage collected.
            if self.is_same_object(obj, JObject::null())? {
                Err(Error::ObjectFreed)
            } else {
                Err(Error::JniCall(JniError::NoMemory))
            }
        } else {
            Ok(global_ref)
        }
    }

    /// Creates a new global reference and casts it to a different type.
    ///
    /// This is a convenience method that combines [`Self::cast_global`] and
    /// [`Self::new_global_ref`].
    ///
    /// It first checks if the object is an instance of the target type, and if so it creates a new
    /// global reference with the target type.
    ///
    /// `obj` can be a local reference or a global reference.
    ///
    /// For upcasting (converting to a more general type), consider using the `AsRef` trait
    /// implementations instead, which don't require runtime checks.
    ///
    /// # Example
    /// ```rust,no_run
    /// # use jni::{jni_sig, jni_str, errors::Result, Env, objects::*};
    /// #
    /// # fn example(env: &mut Env) -> Result<()> {
    /// let local_obj: JObject = env.new_object(jni_str!("java/lang/String"), jni_sig!("()V"), &[])?;
    /// let global_string = env.new_cast_global_ref::<JString>(local_obj)?;
    /// // global_string is now a `Global<JString>` that persists beyond local frames
    ///
    /// // For upcasting, the `AsRef` trait is more efficient:
    /// let as_obj_again: &JObject = global_string.as_ref(); // No runtime check needed
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # Errors
    ///
    /// Returns [`Error::WrongObjectType`] if the object is not an instance of the target type.
    /// Returns [`Error::ClassNotFound`] if the target class cannot be found.
    pub fn new_cast_global_ref<'any_local, To>(
        &self,
        obj: impl Reference + AsRef<JObject<'any_local>>,
    ) -> Result<Global<To::GlobalKind>>
    where
        To: Reference,
    {
        if obj.is_null() {
            return Ok(Default::default());
        }

        if self.is_instance_of_cast_type::<To>(obj.as_ref())? {
            let new = self.new_global_ref(obj)?;
            // Safety:
            // - we have just checked that `new` is an instance of `To`
            unsafe {
                let cast = To::global_kind_from_raw(new.into_raw());
                Ok(Global::new(self, cast))
            }
        } else {
            Err(Error::WrongObjectType)
        }
    }

    /// Creates an auto-delete [`Global`] reference wrapper around a raw JNI `jobject` pointer.
    ///
    /// This may be useful if a third-party library gives you ownership over a JNI global reference
    /// pointer and you want to manage it safely in Rust.
    ///
    /// If you don't own the global reference you must not use this function and can instead
    /// use [`Env::as_cast_raw`] to temporarily wrap the raw pointer without taking ownership.
    ///
    /// # Safety
    /// - The `raw` pointer must be a valid JNI reference of the appropriate type `T`, or `null`.
    /// - The `raw` pointer must not have any other existing wrappers
    /// - You must logically own the global reference and be able to guarantee that it can not
    ///   be deleted elsewhere while the returned [`Global`] is alive.
    pub unsafe fn global_from_raw<T: Reference>(&self, raw: sys::jobject) -> Global<T::GlobalKind> {
        // Safety: the rules above cover the safety requirements
        unsafe { Global::new(self, T::global_kind_from_raw(raw)) }
    }

    /// Attempts to cast an owned global reference to a different type.
    ///
    /// This performs a runtime type check using `IsInstanceOf` and consumes the input reference.
    ///
    /// For upcasting (converting to a more general type), consider using the `AsRef` trait
    /// implementations instead, which don't require runtime checks.
    ///
    /// # Example
    /// ```rust,no_run
    /// # use jni::{jni_sig, jni_str, errors::Result, Env, objects::*};
    /// #
    /// # fn example(env: &mut Env) -> Result<()> {
    /// let local_obj: JObject = env.new_object(jni_str!("java/lang/String"), jni_sig!("()V"), &[])?;
    /// let global_obj: Global<JObject<'static>> = env.new_global_ref(&local_obj)?;
    /// let global_string = env.cast_global::<JString>(global_obj)?;
    ///
    /// // For upcasting, the `AsRef` trait is more efficient:
    /// let as_obj_again: &JObject = global_string.as_ref(); // No runtime check needed
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # Errors
    ///
    /// Returns [`Error::WrongObjectType`] if the object is not an instance of the target type.
    /// Returns [`Error::ClassNotFound`] if the target class cannot be found.
    pub fn cast_global<To>(
        &self,
        obj: Global<
            impl Into<JObject<'static>>
            + AsRef<JObject<'static>>
            + Default
            + Reference
            + Send
            + Sync
            + 'static,
        >,
    ) -> Result<Global<To::GlobalKind>>
    where
        To: Reference,
    {
        if obj.is_null() {
            return Ok(Default::default());
        }

        if self.is_instance_of_cast_type::<To>(obj.as_ref())? {
            // Safety:
            // - we have just checked that `obj` is an instance of `T`
            // - there won't be multiple wrappers since we are creating one from the other
            unsafe {
                let cast = To::global_kind_from_raw(obj.into_raw());
                Ok(Global::new(self, cast))
            }
        } else {
            Err(Error::WrongObjectType)
        }
    }

    /// Creates a new weak global reference.
    ///
    /// Weak global references are a special kind of Java object reference that
    /// doesn't prevent the Java object from being garbage collected. See
    /// [`Weak`] for more information.
    ///
    /// If you use this API to create a [`Weak`] from another [`Weak`]
    /// then it may return [`Error::ObjectFreed`] if the object has been garbage
    /// collected.
    ///
    /// Attempting to create a [`Weak`] for a `null` reference will return an
    /// [`Error::ObjectFreed`] error.
    pub fn new_weak_ref<O>(&self, obj: O) -> Result<Weak<O::GlobalKind>>
    where
        O: Reference,
    {
        // Check if the pointer is null *before* calling `NewWeakGlobalRef`.
        //
        // This avoids a bug in some JVM implementations which, contrary to the JNI specification,
        // will throw `java.lang.OutOfMemoryError: C heap space` from `NewWeakGlobalRef` if it is
        // passed a null pointer. (The specification says it will return a null pointer in that
        // situation, not throw an exception.)
        if obj.is_null() {
            return Err(Error::ObjectFreed);
        }

        // Safety:
        // - the minimum supported JNI version is 1.4
        // - we can assume that `obj.raw()` is a valid reference
        // - we know there's no other wrapper for the reference passed to from_global_raw
        //   since we have just created it.
        let weak_ref = unsafe {
            let weak = O::global_kind_from_raw(jni_call_with_catch!(
                catch |env| {
                    crate::exceptions::JOutOfMemoryError =>
                        Err(Error::JniCall(JniError::NoMemory)),
                    else => Err(Error::JniCall(JniError::Unknown)),
                },
                self,
                v1_2,
                NewWeakGlobalRef,
                obj.as_raw()
            )?);
            Weak::new(self, weak)
        };

        // Unlike for NewLocalRef and NewGlobalRef, the JNI spec doesn't seem to
        // give the same guarantee that it will return null if the object has
        // already been freed, but it seems reasonable to assume it can.

        if weak_ref.is_null() {
            // Unlike for NewLocalRef and NewGlobalRef we can assume that NewWeakGlobalRef
            // will throw an out-of-memory exception (that we catch) instead of returning null
            Err(Error::ObjectFreed)
        } else {
            Ok(weak_ref)
        }
    }

    /// Creates an auto-delete [`Weak`] reference wrapper around a raw JNI `jobject` pointer.
    ///
    /// This may be useful if a third-party library gives you ownership over a JNI weak reference
    /// pointer and you want to manage it safely in Rust.
    ///
    /// If you don't own the weak reference you must not use this function and can instead
    /// use [`Env::as_cast_raw`] to temporarily wrap the raw pointer without taking ownership.
    ///
    /// # Safety
    /// - The `raw` pointer must be a valid JNI reference of the appropriate type `T`, or `null`.
    /// - The `raw` pointer must not have any other existing wrappers
    /// - You must logically own the weak reference and be able to guarantee that it can not
    ///   be deleted elsewhere while the returned [`Weak`] is alive.
    pub unsafe fn weak_from_raw<T: Reference>(&self, raw: sys::jobject) -> Weak<T::GlobalKind> {
        // Safety: the rules above cover the safety requirements
        unsafe { Weak::new(self, T::global_kind_from_raw(raw)) }
    }

    /// Create a new local reference to an object.
    ///
    /// Specifically, this calls the JNI function [`NewLocalRef`], which creates a reference in the
    /// current local reference frame, regardless of whether the original reference belongs to the
    /// same local reference frame, a different one, or is a [global reference][Global]. In Rust
    /// terms, this method accepts a JNI reference with any valid lifetime and produces a clone of
    /// that reference with the lifetime of this `Env`. The returned reference can outlive the
    /// original.
    ///
    /// This method is useful when you have a strong global reference and you can't prevent it from
    /// being dropped before you're finished with it. In that case, you can use this method to
    /// create a new local reference that's guaranteed to remain valid for the duration of the
    /// current local reference frame, regardless of what later happens to the original global
    /// reference.
    ///
    /// # Lifetimes
    ///
    /// `'local` is the lifetime of the local reference frame that this `Env` belongs to. This
    /// method creates a new local reference in that frame, with lifetime `'local`.
    ///
    /// `'other_local` is the lifetime of the original reference's frame. It can be any valid
    /// lifetime, even one that `'local` outlives or vice versa.
    ///
    /// Think of `'local` as meaning `'new` and `'other_local` as meaning `'original`. (It is
    /// unfortunately not possible to actually give these names to the two lifetimes because
    /// `'local` is a parameter to the `Env` type, not a parameter to this method.)
    ///
    /// # Example
    ///
    /// In the following example, the `ExampleError::extract_throwable` method uses
    /// `Env::new_local_ref` to create a new local reference that outlives the original global
    /// reference:
    ///
    /// ```no_run
    /// # use jni::{jni_sig, jni_str, Env, objects::*, strings::*};
    /// # use std::fmt::Display;
    /// #
    /// # type SomeOtherErrorType = Box<dyn Display>;
    /// #
    /// /// An error that may be caused by either a Java exception or something going wrong in Rust
    /// /// code.
    /// enum ExampleError {
    ///     /// This variant represents a Java exception.
    ///     ///
    ///     /// The enclosed `Global` points to a Java object of class `java.lang.Throwable`
    ///     /// (or one of its many subclasses).
    ///     Exception(Global<JObject<'static>>),
    ///
    ///     /// This variant represents an error in Rust code, not a Java exception.
    ///     Other(SomeOtherErrorType),
    /// }
    ///
    /// impl ExampleError {
    ///     /// Consumes this `ExampleError` and produces a `JThrowable`, suitable for throwing
    ///     /// back to Java code.
    ///     ///
    ///     /// If this is an `ExampleError::Exception`, then this extracts the enclosed Java
    ///     /// exception object. Otherwise, a new exception object is created to represent this
    ///     /// error.
    ///     fn extract_throwable<'local>(self, env: &mut Env<'local>) -> jni::errors::Result<JThrowable<'local>> {
    ///         let throwable: JObject = match self {
    ///             ExampleError::Exception(exception) => {
    ///                 // The error was caused by a Java exception.
    ///
    ///                 // Here, `exception` is a `Global` pointing to a Java `Throwable`. It
    ///                 // will be dropped at the end of this `match` arm. We'll use
    ///                 // `new_local_ref` to create a local reference that will outlive the
    ///                 // `Global`.
    ///
    ///                 env.new_local_ref(&exception)?
    ///             }
    ///
    ///             ExampleError::Other(error) => {
    ///                 // The error was caused by something that happened in Rust code. Create a
    ///                 // new `java.lang.Error` to represent it.
    ///
    ///                 let error_string = JString::from_str(env, error.to_string())?;
    ///
    ///                 env.new_object(
    ///                     jni_str!("java/lang/Error"),
    ///                     jni_sig!("(Ljava/lang/String;)V"),
    ///                     &[
    ///                         (&error_string).into(),
    ///                     ],
    ///                 )?
    ///             }
    ///         };
    ///         let throwable = env.cast_local::<JThrowable>(throwable)?;
    ///         Ok(throwable)
    ///     }
    /// }
    /// ```
    ///
    /// [`NewLocalRef`]: https://docs.oracle.com/en/java/javase/11/docs/specs/jni/functions.html#newlocalref
    pub fn new_local_ref<'any_local, O>(&mut self, obj: O) -> Result<O::Kind<'local>>
    where
        O: Reference + AsRef<JObject<'any_local>>,
    {
        // Runtime check that the 'local reference lifetime will be tied to
        // Env lifetime for the top JNI stack frame
        self.assert_top();

        //let obj = obj.as_ref();

        // By checking for `null` before calling `NewLocalRef` we can recognise
        // that a `null` returned from `NewLocalRef` is from being out of memory.
        if obj.is_null() {
            return Ok(O::null());
        }

        // Safety:
        // - the minimum supported JNI version is 1.4
        // - we can assume that `obj.raw()` is a valid reference, or null
        // - we know there's no other wrapper for the reference passed to from_local_raw
        //   since we have just created it.
        let local = unsafe {
            O::kind_from_raw(jni_call_no_post_check_ex!(
                self,
                v1_2,
                NewLocalRef,
                obj.as_raw()
            )?)
        };

        // Per JNI spec, `NewLocalRef` will return a null pointer if the object was GC'd
        // (which could happen if `obj` is a `Weak`):
        //
        //  > it is recommended that a (strong) local or global reference to the
        //  > underlying object be acquired using one of the JNI functions
        //  > NewLocalRef or NewGlobalRef. These functions will return NULL if
        //  > the object has been freed.
        //
        if local.is_null() {
            // In this case it's ambiguous whether there has been an out-of-memory error or
            // the object has been garbage collected and so we now _explicitly_ check
            // whether the object has been garbage collected.
            if self.is_same_object(obj, JObject::null())? {
                Err(Error::ObjectFreed)
            } else {
                Err(Error::JniCall(JniError::NoMemory))
            }
        } else {
            Ok(local)
        }
    }

    /// Creates a new local reference and casts it to a different type.
    ///
    /// This is a convenience method that combines [`Self::cast_local`] and [`Self::new_local_ref`].
    ///
    /// This performs a runtime type check using `IsInstanceOf` and then creates a new local
    /// reference.
    ///
    /// `obj` can be a local reference or a global reference.
    ///
    /// For upcasting (converting to a more general type), consider using the `From` trait
    /// implementations instead, which don't require runtime checks.
    ///
    /// # Example
    /// ```rust,no_run
    /// # use jni::{jni_sig, jni_str, errors::Result, Env, objects::*};
    /// #
    /// # fn example(env: &mut Env) -> Result<()> {
    /// let local_obj: JObject = env.new_object(jni_str!("java/lang/String"), jni_sig!("()V"), &[])?;
    /// let local_string = env.new_cast_local_ref::<JString>(&local_obj)?;
    /// // local_string is now a JString<'local> in the current frame
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # Errors
    ///
    /// Returns [`Error::WrongObjectType`] if the object is not an instance of the target type.
    /// Returns [`Error::ClassNotFound`] if the target class cannot be found.
    pub fn new_cast_local_ref<'any_local, To>(
        &mut self,
        obj: impl Reference + AsRef<JObject<'any_local>>,
    ) -> Result<To::Kind<'local>>
    where
        To: Reference,
    {
        if obj.is_null() {
            return Ok(To::null());
        }

        if self.is_instance_of_cast_type::<To>(obj.as_ref())? {
            let new = self.new_local_ref(obj.as_ref())?;
            // Safety:
            // - we have just checked that `new` is an instance of `To`
            // - as it's a new reference, it's assigned the `'local` Env lifetime
            unsafe { Ok(To::kind_from_raw::<'local>(new.into_raw())) }
        } else {
            Err(Error::WrongObjectType)
        }
    }

    /// Attempts to cast an owned local reference to a different type.
    ///
    /// This performs a runtime type check using `IsInstanceOf` and consumes the input reference.
    /// For upcasting (converting to a more general type), consider using the `From` trait
    /// implementations instead, which don't require runtime checks.
    ///
    /// # Example
    /// ```rust,no_run
    /// # use jni::{jni_sig, jni_str, errors::Result, Env, objects::*};
    /// #
    /// # fn example(env: &mut Env) -> Result<()> {
    /// let obj: JObject = env.new_object(jni_str!("java/lang/String"), jni_sig!("()V"), &[])?;
    /// let string: JString = env.cast_local::<JString>(obj)?;
    ///
    /// // For upcasting, From trait is more efficient:
    /// let obj_again: JObject = string.into(); // No runtime check needed
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # Errors
    ///
    /// Returns [`Error::WrongObjectType`] if the object is not an instance of the target type.
    /// Returns [`Error::ClassNotFound`] if the target class cannot be found.
    pub fn cast_local<'any_local, To>(
        &self,
        obj: impl Reference + Into<JObject<'any_local>> + AsRef<JObject<'any_local>>,
    ) -> Result<To::Kind<'any_local>>
    where
        To: Reference,
    {
        if obj.is_null() {
            return Ok(To::null::<'any_local>());
        }

        if self.is_instance_of_cast_type::<To>(obj.as_ref())? {
            let obj: JObject = obj.into();
            // Safety:
            // - we have just checked that `obj` is an instance of `T`
            // - it is associated with the same lifetime that it was created with
            unsafe { Ok(To::kind_from_raw::<'any_local>(obj.into_raw())) }
        } else {
            Err(Error::WrongObjectType)
        }
    }

    /// Attempts to cast a reference (local or global) to a different type
    /// without consuming it.
    ///
    /// This method borrows the input reference and returns a wrapper that
    /// derefs to the target type. The original reference remains valid and can
    /// be used after the cast operation.
    ///
    /// # Example
    /// ```rust,no_run
    /// # use jni::{jni_sig, jni_str, errors::Result, Env, objects::*};
    /// #
    /// # fn example(env: &mut Env) -> Result<()> {
    /// let obj: JObject = env.new_object(jni_str!("java/lang/String"), jni_sig!("()V"), &[])?;
    /// let string_ref = env.as_cast::<JString>(&obj)?;
    /// // obj is still valid here
    /// let empty_string_contents = string_ref.to_string();
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # Errors
    ///
    /// Returns [`Error::WrongObjectType`] if the object is not an instance of
    /// the target type. Returns [`Error::ClassNotFound`] if the target class
    /// cannot be found.
    pub fn as_cast<'from, 'any, To>(
        &self,
        obj: &'from (impl Reference + AsRef<JObject<'any>>),
    ) -> Result<Cast<'from, 'any, To>>
    where
        To: Reference,
        'any: 'from,
    {
        Cast::new(self, obj)
    }

    /// Cast a reference (local or global) to a different type without consuming
    /// it and without any runtime checks.
    ///
    /// This method borrows the input reference and returns a wrapper that
    /// derefs to the target type. The original reference remains valid and can
    /// be used after the cast operation.
    ///
    /// # Example
    /// ```rust,no_run
    /// # use jni::{jni_sig, jni_str, errors::Result, Env, objects::*};
    /// #
    /// # fn example(env: &mut Env) -> Result<()> {
    /// let obj: JObject = env.new_object(jni_str!("java/lang/String"), jni_sig!("()V"), &[])?;
    /// let string_ref = unsafe { env.as_cast_unchecked::<JString>(&obj) };
    /// // obj is still valid here
    /// let empty_string_contents = string_ref.to_string();
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # Safety
    ///
    /// The caller must ensure that `obj` is a valid instance of `To`, or
    /// `null`.
    pub unsafe fn as_cast_unchecked<'from, 'any, To>(
        &self,
        obj: &'from (impl Reference + AsRef<JObject<'any>>),
    ) -> Cast<'from, 'any, To>
    where
        To: Reference,
        'any: 'from,
    {
        // Safety: the caller must ensure that `obj` is a valid instance of `To`, or `null`.
        unsafe { Cast::new_unchecked(obj) }
    }

    /// Attempts to cast a raw [`jobject`] reference without taking ownership.
    ///
    /// This method borrows the input reference and returns a wrapper that
    /// derefs to the target type. The original reference remains valid and can
    /// continue to be used.
    ///
    /// # Example
    /// ```rust,no_run
    /// # use jni::{errors::Result, Env, objects::*, sys::jobject};
    /// #
    /// # fn example(env: &mut Env, raw_global: jobject) -> Result<()> {
    /// // SAFETY: we know that raw_global is a valid java.lang.String reference
    /// let string_ref = unsafe { env.as_cast_raw::<Global<JString>>(&raw_global)? };
    /// let string_contents = string_ref.to_string();
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # Errors
    ///
    /// Returns [`Error::WrongObjectType`] if the object is not an instance of
    /// the target type. Returns [`Error::ClassNotFound`] if the target class
    /// cannot be found.
    ///
    /// # Safety
    ///
    /// The caller must ensure that `from` is a valid reference (local or
    /// global) - which may be `null`.
    ///
    /// The caller must ensure the `from` reference will not be deleted while
    /// the `Cast` exists.
    ///
    /// Note: even though this API is `unsafe`, it will still do a runtime check
    /// that `from` is a valid instance of `To`, so you are not required to know
    /// this.
    ///
    /// Note: this API is agnostic about whether the reference is local or
    /// global because the returned [`Cast`] wrapper doesn't give ownership over
    /// the reference and so you can't accidentally attempt to delete it using
    /// the wrong JNI API.
    pub unsafe fn as_cast_raw<'from, To>(
        &self,
        from: &'from jobject,
    ) -> Result<Cast<'from, 'from, To>>
    where
        To: Reference,
    {
        // Safety: the rules in the doc comment cover the `from_raw` safety requirements
        unsafe { Cast::from_raw(self, from) }
    }

    /// Creates a new auto-deleted local reference.
    ///
    /// See also [`with_local_frame`](struct.Env.html#method.with_local_frame) method that
    /// can be more convenient when you create a _bounded_ number of local references
    /// but cannot rely on automatic de-allocation (e.g., in case of recursion, deep call stacks,
    /// [permanently-attached](struct.JavaVM.html#attaching-native-threads) native threads, etc.).
    #[deprecated = "Use '.auto()' from IntoAuto trait"]
    pub fn auto_local<O>(&self, obj: O) -> Auto<'local, O>
    where
        O: Into<JObject<'local>>,
    {
        Auto::new(obj)
    }

    /// Deletes a local reference early, before its JNI stack frame unwinds.
    ///
    /// Local references exist within a JNI stack frame, which would typically be created by the
    /// Java VM before making a native method call, and then unwound when your native method
    /// returns.
    ///
    /// New JNI stack frames may also be created via [`Self::with_local_frame`].
    ///
    /// Typically you don't have to worry about deleting local references since they are
    /// automatically freed when the JNI stack frame they were created in unwinds.
    ///
    /// But, each local reference takes memory and so you need to make sure to not excessively
    /// allocate local references.
    ///
    /// If you find that you are allocating a large number of local references in a single native
    /// method call, (e.g. while looping over a large collection), this API can be used to
    /// explicitly delete local references before the JNI stack frame unwinds.
    ///
    /// In most cases it is better to use [`Auto`] (see [`IntoAuto::auto`] method) or
    /// [`Self::with_local_frame`] instead of directly calling [`Self::delete_local_ref`].
    pub fn delete_local_ref<'other_local, O>(&self, obj: O)
    where
        O: Into<JObject<'other_local>>,
    {
        let obj = obj.into();
        let raw = obj.into_raw();

        // Safety:
        // `raw` may be `null`
        // DeleteLocalRef is safe to call while there may be a pending exception
        unsafe {
            ex_safe_jni_call_no_post_check_ex!(self, v1_1, DeleteLocalRef, raw);
        }
    }

    /// Creates a new local reference frame, in which at least a given number
    /// of local references can be created.
    ///
    /// Returns `Err` on failure, with a pending `OutOfMemoryError`.
    ///
    /// Prefer to use
    /// [`with_local_frame`](struct.Env.html#method.with_local_frame)
    /// instead of direct `push_local_frame`/`pop_local_frame` calls.
    ///
    /// # Safety
    ///
    /// The caller must guarantee that there will be a corresponding call to
    /// `pop_local_frame`
    ///
    /// The caller must ensure that a new `AttachGuard` is created before
    /// creating a new local frame and the local frame may only access
    /// a `Env` that is borrowed from this new guard (so that local
    /// references will be tied to lifetime of the new guard)
    unsafe fn push_local_frame(&self, capacity: i32) -> Result<()> {
        // Safety:
        // This method is safe to call in case of pending exceptions (see chapter 2 of the spec)
        // We check for JNI > 1.2 in `from_raw`
        let res =
            unsafe { ex_safe_jni_call_no_post_check_ex!(self, v1_2, PushLocalFrame, capacity) };
        jni_error_code_to_result(res)
    }

    /// Pops off the current local reference frame, frees all the local
    /// references allocated on the current stack frame, except the `result`,
    /// which is returned from this function and remains valid.
    ///
    /// The resulting `JObject` will be `NULL` iff `result` is `NULL`.
    ///
    /// This method allows direct control of local frames, but it can cause
    /// undefined behavior and is therefore unsafe. Prefer
    /// [`Env::with_local_frame`] instead.
    ///
    /// # Safety
    ///
    /// Any local references created after the most recent call to
    /// [`Env::push_local_frame`] (or the underlying JNI function) must not
    /// be used after calling this method.
    ///
    /// The `AttachGuard` created before calling `push_local_frame` must be
    /// dropped after calling `pop_local_frame`.
    unsafe fn pop_local_frame<'frame_local, T: Reference>(
        &self,
        result: T::Kind<'frame_local>,
    ) -> Result<T::Kind<'local>> {
        let result: JObject<'frame_local> = result.into();
        // Safety:
        // This method is safe to call in case of pending exceptions (see chapter 2 of the spec)
        // We check for JNI > 1.2 in `from_raw`
        unsafe {
            let raw =
                ex_safe_jni_call_no_post_check_ex!(self, v1_2, PopLocalFrame, result.into_raw());
            Ok(T::kind_from_raw(raw))
        }
    }

    /// Run a closure with a mutable [`Env`] associated with a new local reference frame.
    ///
    /// `capacity` is the minimum number of local references that can be created in the new frame.
    /// it can be seen as a hint to the JVM to pre-allocate space for that many local references
    /// but if more are created then the JVM will transparently allocate more space as needed.
    ///
    /// If a frame can't be allocated with the requested capacity for local references, returns
    /// `Err` with a pending `OutOfMemoryError`.
    ///
    /// Once this method returns, all references allocated in the frame are freed.
    ///
    /// If you need to return a reference from the frame to the caller then you should either
    /// use [`Self::with_local_frame_returning_local`] or else create a [`Global`] with
    /// [`Self::new_global_ref`].
    ///
    /// # Runtime Top Frame Checks
    ///
    /// See top-level [Env] documentation for rules on limiting yourself to one
    /// [Env] reference per-scope to avoid exposing code to runtime checks for
    /// the top JNI frame (that can panic).
    pub fn with_local_frame<F, T, E>(&self, capacity: usize, f: F) -> std::result::Result<T, E>
    where
        F: FnOnce(&mut Env) -> std::result::Result<T, E>,
        E: From<Error>,
    {
        let capacity: jni_sys::jint = capacity
            .try_into()
            .map_err(|_| Error::JniCall(JniError::InvalidArguments))?;

        unsafe {
            // Safety: by creating a new AttachGuard we ensure that the attach guard level
            // will be incremented in sync with the creation of a new JNI stack frame
            let mut guard = AttachGuard::from_unowned(self.get_raw());
            let env = guard.borrow_env_mut();
            self.push_local_frame(capacity)?;
            let ret = catch_unwind(AssertUnwindSafe(|| f(env)));
            self.pop_local_frame::<JObject>(JObject::null())?;
            drop(guard);

            match ret {
                Ok(ret) => ret,
                Err(payload) => {
                    resume_unwind(payload);
                }
            }
        }
    }

    /// Run a closure with a mutable [`Env`] associated with a new local reference frame, and return
    /// one local reference to the caller.
    ///
    /// `capacity` is the minimum number of local references that can be created in the new frame.
    /// it can be seen as a hint to the JVM to pre-allocate space for that many local references but
    /// if more are created then the JVM will transparently allocate more space as needed.
    ///
    /// If a frame can't be allocated with the requested capacity for local references, returns
    /// `Err` with a pending `OutOfMemoryError`.
    ///
    /// Once this method returns, all references allocated in the frame are freed, except the one
    /// that the function returns, which remains valid.
    ///
    /// Since the low-level JNI interface has support for passing back a single local reference from
    /// a local frame as special-case optimization, this alternative to `with_local_frame` exposes
    /// that capability to return a local reference without needing to create a temporary
    /// [`Global`].
    pub fn with_local_frame_returning_local<F, T, E>(
        &mut self,
        capacity: usize,
        f: F,
    ) -> std::result::Result<T::Kind<'local>, E>
    where
        F: for<'new_local> FnOnce(
            &mut Env<'new_local>,
        ) -> std::result::Result<T::Kind<'new_local>, E>,
        T: Reference,
        E: From<Error>,
    {
        // Runtime check that the 'local reference lifetime will be tied to
        // Env lifetime for the top JNI stack frame
        self.assert_top();

        let capacity: jni_sys::jint = capacity
            .try_into()
            .map_err(|_| Error::JniCall(JniError::InvalidArguments))?;

        unsafe {
            // Inner scope to ensure drop order: `Result` -> `env` -> `guard`, before we potentially call `resume_unwind`.
            let panic_payload = {
                // Safety: by creating a new AttachGuard we ensure that the attach guard level
                // will be incremented in sync with the creation of a new JNI stack frame
                let mut guard = AttachGuard::from_unowned(self.get_raw());
                let env = guard.borrow_env_mut();

                self.push_local_frame(capacity)?;

                match catch_unwind(AssertUnwindSafe(|| f(env))) {
                    Ok(Ok(obj)) => {
                        let obj = self.pop_local_frame::<T>(obj)?;
                        return Ok(obj);
                    }
                    Ok(Err(err)) => {
                        self.pop_local_frame::<T>(T::null())?;
                        return Err(err);
                    }
                    Err(payload) => {
                        self.pop_local_frame::<T>(T::null())?;
                        payload
                    }
                }
            };

            resume_unwind(panic_payload);
        }
    }

    /// Runs a closure with a mutable [`Env`] associated with the top local reference frame.
    ///
    /// Unlike [`Self::with_local_frame()`], this API does not push a new JNI stack frame and so new
    /// local references created in the closure will be associated with the existing local reference
    /// frame at the top of the stack.
    ///
    /// Most of the time this API should probably be avoided (see [`Self::with_local_frame`]).
    ///
    /// Only use if:
    /// - You're sure your code won't leak local references into the current stack frame.
    /// - OR, you're sure that the leaked references are acceptable because you know when the top
    ///   frame will unwind and release those references.
    ///
    /// This will have a slightly lower overhead than [`Self::with_local_frame()`] (since it doesn't
    /// need to push/pop a JNI stack frame), but the trade off is that you may leak local references
    /// into the top stack frame.
    ///
    /// Keep in mind that deleting local references individually is likely to have a higher cost
    /// than pushing/popping a JNI stack frame, so you should probably only use this API if you're
    /// OK with leaking a small number of local references into the top frame and waiting for it to
    /// unwind.
    ///
    /// # Runtime Top Frame Checks
    ///
    /// See top-level [Env] documentation for rules on limiting yourself to one [Env] reference
    /// per-scope to avoid exposing code to runtime checks for the top JNI frame (that can panic).
    pub fn with_top_local_frame<F, T, E>(&self, f: F) -> std::result::Result<T, E>
    where
        F: FnOnce(&mut Env) -> std::result::Result<T, E>,
        E: From<Error>,
    {
        unsafe {
            let mut guard = AttachGuard::from_unowned(self.get_raw());
            f(guard.borrow_env_mut())
        }
    }

    /// Allocates a new object from a class descriptor without running a
    /// constructor.
    ///
    /// - Returns [`Error::Instantiation`] if an `InstantiationException`
    ///   occurs, if the class is an interface or an abstract class.
    /// - Returns [`Error::JniCall`] + [`JniError::NoMemory`] if an
    ///   `OutOfMemoryError` exception occurs.
    ///
    /// This API catches exceptions internally and is not expected to return
    /// [`Error::JavaException`] (unless called while there is a pending exception).
    pub fn alloc_object<'other_local, T>(&mut self, class: T) -> Result<JObject<'local>>
    where
        T: Desc<'local, JClass<'other_local>>,
    {
        // Runtime check that the 'local reference lifetime will be tied to
        // Env lifetime for the top JNI stack frame
        self.assert_top();
        let class = class.lookup(self)?;
        let obj = unsafe {
            jni_call_with_catch_and_null_check!(
                catch |env| {
                    crate::exceptions::JInstantiationException =>
                        Err(Error::Instantiation),
                    crate::exceptions::JOutOfMemoryError =>
                        Err(Error::JniCall(JniError::NoMemory)),
                    else => Err(Error::NullPtr("Unexpected Exception")),
                },
                self, v1_1, AllocObject, class.as_ref().as_raw())?
        };

        // Ensure that `class` isn't dropped before the JNI call returns.
        drop(class);

        Ok(unsafe { JObject::from_raw(self, obj) })
    }

    // FIXME: this API shouldn't need a `&mut self` reference since it doesn't return a local reference
    // (currently it just needs the `&mut self` for the sake of `Desc<JClass>::lookup`)
    //
    /// Look up a method by class descriptor, name, and signature.
    ///
    /// # Example
    /// ```rust,no_run
    /// # use jni::{jni_sig, jni_str, errors::Result, Env, objects::JMethodID};
    /// #
    /// # fn example(env: &mut Env) -> Result<()> {
    /// let method_id: JMethodID =
    ///     env.get_method_id(jni_str!("java/lang/String"), jni_str!("substring"), jni_sig!("(II)Ljava/lang/String;"))?;
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// Returns a valid method ID on success or [`Error::MethodNotFound`] on failure.
    ///
    /// Returns [`Error::JniCall`] + [`JniError::NoMemory`] if an `OutOfMemoryError` is thrown by
    /// the JVM.
    ///
    /// This API catches exceptions internally and is not expected to return
    /// [`Error::JavaException`] (unless called while there is a pending exception).
    pub fn get_method_id<'other_local, 'sig, 'sig_args, C, N, S>(
        &mut self,
        class: C,
        name: N,
        sig: S,
    ) -> Result<JMethodID>
    where
        C: Desc<'local, JClass<'other_local>>,
        N: AsRef<JNIStr>,
        S: AsRef<MethodSignature<'sig, 'sig_args>>,
    {
        let class = class.lookup(self)?;
        let ffi_name = name.as_ref();
        let sig = sig.as_ref();

        let method_id = unsafe {
            jni_call_with_catch!(
                catch |env| {
                    crate::exceptions::JNoSuchMethodError =>
                        Err(Error::MethodNotFound {
                            name: ffi_name.to_string(),
                            sig: sig.sig().to_string(),
                        }),
                    e: crate::exceptions::JExceptionInInitializerError => {
                        let exception = e.get_exception(env);
                        let exception = if let Ok(exception) = exception {
                            env.new_global_ref(exception).ok()
                        } else {
                            None
                        };
                        Err(Error::ExceptionInInitializer { exception })
                    },
                    crate::exceptions::JOutOfMemoryError =>
                        Err(Error::JniCall(JniError::NoMemory)),
                    else => Err(Error::JniCall(JniError::Unknown)),
                },
                self,
                v1_1,
                GetMethodID,
                class.as_ref().as_raw(),
                ffi_name.as_ptr(),
                sig.as_ref().sig().as_ptr()
            )?
        };

        // Ensure that `class` isn't dropped before the JNI call returns.
        drop(class);

        assert!(
            !method_id.is_null(),
            "Spurious null method ID returned, without a pending exception"
        );

        Ok(unsafe { JMethodID::from_raw(method_id) })
    }

    // FIXME: this API shouldn't need a `&mut self` reference since it doesn't return a local reference
    // (currently it just needs the `&mut self` for the sake of `Desc<JClass>::lookup`)
    //
    /// Look up a static method by class descriptor, name, and signature.
    ///
    /// # Example
    /// ```rust,no_run
    /// # use jni::{jni_sig, jni_str, errors::Result, Env, objects::JStaticMethodID};
    /// # fn example(env: &mut Env) -> Result<()> {
    /// let method_id: JStaticMethodID =
    ///     env.get_static_method_id(jni_str!("java/lang/String"), jni_str!("valueOf"), jni_sig!("(I)Ljava/lang/String;"))?;
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// Returns a valid method ID on success or [`Error::MethodNotFound`] on failure.
    ///
    /// Returns [`Error::JniCall`] + [`JniError::NoMemory`] if an `OutOfMemoryError` is thrown by
    /// the JVM.
    ///
    /// This API catches exceptions internally and is not expected to return
    /// [`Error::JavaException`] (unless called while there is a pending exception).
    pub fn get_static_method_id<'other_local, 'sig, 'sig_args, C, N, S>(
        &mut self,
        class: C,
        name: N,
        sig: S,
    ) -> Result<JStaticMethodID>
    where
        C: Desc<'local, JClass<'other_local>>,
        N: AsRef<JNIStr>,
        S: AsRef<MethodSignature<'sig, 'sig_args>>,
    {
        let class = class.lookup(self)?;
        let ffi_name = name.as_ref();
        let sig = sig.as_ref();

        let method_id = unsafe {
            jni_call_with_catch!(
                catch |env| {
                    crate::exceptions::JNoSuchMethodError =>
                        Err(Error::MethodNotFound {
                            name: ffi_name.to_string(),
                            sig: sig.sig().to_string(),
                        }),
                    e: crate::exceptions::JExceptionInInitializerError => {
                        let exception = e.get_exception(env);
                        let exception = if let Ok(exception) = exception {
                            env.new_global_ref(exception).ok()
                        } else {
                            None
                        };
                        Err(Error::ExceptionInInitializer { exception })
                    },
                    crate::exceptions::JOutOfMemoryError =>
                        Err(Error::JniCall(JniError::NoMemory)),
                    else => Err(Error::JniCall(JniError::Unknown)),
                },
                self,
                v1_1,
                GetStaticMethodID,
                class.as_ref().as_raw(),
                ffi_name.as_ptr(),
                sig.as_ref().sig().as_ptr()
            )?
        };

        // Ensure that `class` isn't dropped before the JNI call returns.
        drop(class);

        assert!(
            !method_id.is_null(),
            "Spurious null method ID returned, without a pending exception"
        );

        Ok(unsafe { JStaticMethodID::from_raw(method_id) })
    }

    // FIXME: this API shouldn't need a `&mut self` reference since it doesn't return a local reference
    // (currently it just needs the `&mut self` for the sake of `Desc<JClass>::lookup`)
    //
    /// Look up the field ID for a class/name/type combination.
    ///
    /// # Example
    /// ```rust,no_run
    /// # use jni::{jni_sig, jni_str, errors::Result, Env, objects::JFieldID};
    /// #
    /// # fn example(env: &mut Env) -> Result<()> {
    /// let field_id: JFieldID = env.get_field_id(jni_str!("com/my/Class"), jni_str!("intField"), jni_sig!("I"))?;
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// Returns a valid field ID on success or [`Error::FieldNotFound`] on failure.
    ///
    /// Returns [`Error::JniCall`] + [`JniError::NoMemory`] if an `OutOfMemoryError` is thrown by
    /// the JVM.
    ///
    /// This API catches exceptions internally and is not expected to return
    /// [`Error::JavaException`] (unless called while there is a pending exception).
    pub fn get_field_id<'other_local, 'sig, C, N, S>(
        &mut self,
        class: C,
        name: N,
        sig: S,
    ) -> Result<JFieldID>
    where
        C: Desc<'local, JClass<'other_local>>,
        N: AsRef<JNIStr>,
        S: AsRef<FieldSignature<'sig>>,
    {
        let class = class.lookup(self)?;
        let ffi_name = name.as_ref();
        let ffi_sig = sig.as_ref();

        let field_id = unsafe {
            jni_call_with_catch!(
                catch |env| {
                    crate::exceptions::JNoSuchFieldError =>
                        Err(Error::FieldNotFound {
                            name: ffi_name.to_string(),
                            sig: ffi_sig.sig().to_string(),
                        }),
                    e: crate::exceptions::JExceptionInInitializerError => {
                        let exception = e.get_exception(env);
                        let exception = if let Ok(exception) = exception {
                            env.new_global_ref(exception).ok()
                        } else {
                            None
                        };
                        Err(Error::ExceptionInInitializer { exception })
                    },
                    crate::exceptions::JOutOfMemoryError =>
                        Err(Error::JniCall(JniError::NoMemory)),
                    else => Err(Error::JniCall(JniError::Unknown)),
                },
                self,
                v1_1,
                GetFieldID,
                class.as_ref().as_raw(),
                ffi_name.as_ptr(),
                ffi_sig.sig().as_ptr()
            )?
        };

        // Ensure that `class` isn't dropped before the JNI call returns.
        drop(class);

        assert!(
            !field_id.is_null(),
            "Spurious null field ID returned with no exception"
        );

        Ok(unsafe { JFieldID::from_raw(field_id) })
    }

    // FIXME: this API shouldn't need a `&mut self` reference since it doesn't return a local reference
    // (currently it just needs the `&mut self` for the sake of `Desc<JClass>::lookup`)
    //
    /// Look up the static field ID for a class/name/type combination.
    ///
    /// # Example
    /// ```rust,no_run
    /// # use jni::{jni_sig, jni_str, errors::Result, Env, objects::JStaticFieldID};
    /// #
    /// # fn example(env: &mut Env) -> Result<()> {
    /// let field_id: JStaticFieldID = env.get_static_field_id(jni_str!("com/my/Class"), jni_str!("intField"), jni_sig!("I"))?;
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// Returns a valid field ID on success or [`Error::FieldNotFound`] on failure.
    ///
    /// Returns [`Error::JniCall`] + [`JniError::NoMemory`] if an `OutOfMemoryError` is thrown by
    /// the JVM.
    ///
    /// This API catches exceptions internally and is not expected to return
    /// [`Error::JavaException`] (unless called while there is a pending exception).
    pub fn get_static_field_id<'other_local, 'sig, T, U, V>(
        &mut self,
        class: T,
        name: U,
        sig: V,
    ) -> Result<JStaticFieldID>
    where
        T: Desc<'local, JClass<'other_local>>,
        U: AsRef<JNIStr>,
        V: AsRef<FieldSignature<'sig>>,
    {
        let class = class.lookup(self)?;
        let ffi_name = name.as_ref();
        let ffi_sig = sig.as_ref();

        let field_id = unsafe {
            jni_call_with_catch!(
                catch |env| {
                    crate::exceptions::JNoSuchFieldError =>
                        Err(Error::FieldNotFound {
                            name: ffi_name.to_string(),
                            sig: ffi_sig.sig().to_string(),
                        }),
                    e: crate::exceptions::JExceptionInInitializerError => {
                        let exception = e.get_exception(env);
                        let exception = if let Ok(exception) = exception {
                            env.new_global_ref(exception).ok()
                        } else {
                            None
                        };
                        Err(Error::ExceptionInInitializer { exception })
                    },
                    crate::exceptions::JOutOfMemoryError =>
                        Err(Error::JniCall(JniError::NoMemory)),
                    else => Err(Error::JniCall(JniError::Unknown)),
                },
                self,
                v1_1,
                GetStaticFieldID,
                class.as_ref().as_raw(),
                ffi_name.as_ptr(),
                ffi_sig.sig().as_ptr()
            )?
        };

        // Ensure that `class` isn't dropped before the JNI call returns.
        drop(class);

        assert!(
            !field_id.is_null(),
            "Spurious null field ID returned with no exception"
        );

        Ok(unsafe { JStaticFieldID::from_raw(field_id) })
    }

    /// Get the class for an object.
    pub fn get_object_class<'other_local, O>(&mut self, obj: O) -> Result<JClass<'local>>
    where
        O: AsRef<JObject<'other_local>>,
    {
        // Runtime check that the 'local reference lifetime will be tied to
        // Env lifetime for the top JNI stack frame
        self.assert_top();
        let obj = obj.as_ref();
        let obj = null_check!(obj, "get_object_class")?;
        unsafe {
            Ok(JClass::from_raw(
                self,
                jni_call_no_post_check_ex!(self, v1_1, GetObjectClass, obj.as_raw())?,
            ))
        }
    }

    /// Call a static method in an unsafe manner. This does nothing to check
    /// whether the method is valid to call on the class, whether the return
    /// type is correct, or whether the number of args is valid for the method.
    ///
    /// Under the hood, this simply calls the `CallStatic<Type>MethodA` method
    /// with the provided arguments.
    ///
    /// # Safety
    ///
    /// The provided JMethodID must be valid, and match the types and number of arguments, and return type.
    /// If these are incorrect, the JVM may crash. The JMethodID must also match the passed type.
    pub unsafe fn call_static_method_unchecked<'other_local, T, U>(
        &mut self,
        class: T,
        method_id: U,
        ret: ReturnType,
        args: &[jvalue],
    ) -> Result<JValueOwned<'local>>
    where
        T: Desc<'local, JClass<'other_local>>,
        U: Desc<'local, JStaticMethodID>,
    {
        // Runtime check that the 'local reference lifetime will be tied to
        // Env lifetime for the top JNI stack frame
        self.assert_top();
        use super::signature::Primitive::{
            Boolean, Byte, Char, Double, Float, Int, Long, Short, Void,
        };
        use JavaType::{Array, Object, Primitive};

        let class = class.lookup(self)?;

        let method_id = method_id.lookup(self)?.as_ref().into_raw();

        let class_raw = class.as_ref().as_raw();
        let jni_args = args.as_ptr();

        macro_rules! invoke {
            ($call:ident -> $ret:ty) => {{
                let o: $ret =
                    jni_call_post_check_ex!(self, v1_1, $call, class_raw, method_id, jni_args)?;
                o
            }};
        }

        // Safety: we're sure we're calling the correct JNI method based on `ret` type
        let ret = unsafe {
            match ret {
                Object | Array => {
                    let obj = invoke!(CallStaticObjectMethodA -> jobject);
                    let obj = JObject::from_raw(self, obj);
                    JValueOwned::from(obj)
                }
                Primitive(Boolean) => invoke!(CallStaticBooleanMethodA -> bool).into(),
                Primitive(Char) => invoke!(CallStaticCharMethodA -> u16).into(),
                Primitive(Byte) => invoke!(CallStaticByteMethodA -> i8).into(),
                Primitive(Short) => invoke!(CallStaticShortMethodA -> i16).into(),
                Primitive(Int) => invoke!(CallStaticIntMethodA -> i32).into(),
                Primitive(Long) => invoke!(CallStaticLongMethodA -> i64).into(),
                Primitive(Float) => invoke!(CallStaticFloatMethodA -> f32).into(),
                Primitive(Double) => invoke!(CallStaticDoubleMethodA -> f64).into(),
                Primitive(Void) => {
                    jni_call_post_check_ex!(
                        self,
                        v1_1,
                        CallStaticVoidMethodA,
                        class_raw,
                        method_id,
                        jni_args
                    )?;
                    JValueOwned::Void
                }
            }
        };

        // Ensure that `class` isn't dropped before the JNI call returns.
        drop(class);

        Ok(ret)
    }

    /// Call an object method in an unsafe manner. This does nothing to check
    /// whether the method is valid to call on the object, whether the return
    /// type is correct, or whether the number of args is valid for the method.
    ///
    /// Under the hood, this simply calls the `Call<Type>MethodA` method with
    /// the provided arguments.
    ///
    /// # Safety
    ///
    /// The provided JMethodID must be valid, and match the types and number of arguments, and return type.
    /// If these are incorrect, the JVM may crash. The JMethodID must also match the passed type.
    pub unsafe fn call_method_unchecked<'other_local, O, T>(
        &mut self,
        obj: O,
        method_id: T,
        ret_ty: ReturnType,
        args: &[jvalue],
    ) -> Result<JValueOwned<'local>>
    where
        O: AsRef<JObject<'other_local>>,
        T: Desc<'local, JMethodID>,
    {
        // Runtime check that the 'local reference lifetime will be tied to
        // Env lifetime for the top JNI stack frame
        self.assert_top();
        use super::signature::Primitive::{
            Boolean, Byte, Char, Double, Float, Int, Long, Short, Void,
        };
        use JavaType::{Array, Object, Primitive};

        let method_id = method_id.lookup(self)?.as_ref().into_raw();

        let obj = obj.as_ref().as_raw();

        let jni_args = args.as_ptr();

        macro_rules! invoke {
            ($call:ident -> $ret:ty) => {{
                let o: $ret = jni_call_post_check_ex!(self, v1_1, $call, obj, method_id, jni_args)?;
                o
            }};
        }

        // Safety: we're sure we're calling the correct JNI method based on `ret_ty` type
        let ret = unsafe {
            match ret_ty {
                Object | Array => {
                    let obj = invoke!(CallObjectMethodA -> jobject);
                    let obj = JObject::from_raw(self, obj);
                    JValueOwned::from(obj)
                }
                Primitive(Boolean) => invoke!(CallBooleanMethodA -> bool).into(),
                Primitive(Char) => invoke!(CallCharMethodA -> u16).into(),
                Primitive(Byte) => invoke!(CallByteMethodA -> i8).into(),
                Primitive(Short) => invoke!(CallShortMethodA -> i16).into(),
                Primitive(Int) => invoke!(CallIntMethodA -> i32).into(),
                Primitive(Long) => invoke!(CallLongMethodA -> i64).into(),
                Primitive(Float) => invoke!(CallFloatMethodA -> f32).into(),
                Primitive(Double) => invoke!(CallDoubleMethodA -> f64).into(),
                Primitive(Void) => {
                    jni_call_post_check_ex!(self, v1_1, CallVoidMethodA, obj, method_id, jni_args)?;
                    JValueOwned::Void
                }
            }
        };

        Ok(ret)
    }

    /// Call an non-virtual object method in an unsafe manner. This does nothing to check
    /// whether the method is valid to call on the object, whether the return
    /// type is correct, or whether the number of args is valid for the method.
    ///
    /// Under the hood, this simply calls the `CallNonvirtual<Type>MethodA` method with
    /// the provided arguments.
    ///
    /// # Safety
    ///
    /// The provided JClass, JMethodID must be valid, and match the types and number of arguments, and return type.
    /// If these are incorrect, the JVM may crash. The JMethodID must also match the passed type.
    pub unsafe fn call_nonvirtual_method_unchecked<'other_local, O, T, U>(
        &mut self,
        obj: O,
        class: T,
        method_id: U,
        ret_ty: ReturnType,
        args: &[jvalue],
    ) -> Result<JValueOwned<'local>>
    where
        O: AsRef<JObject<'other_local>>,
        T: Desc<'local, JClass<'other_local>>,
        U: Desc<'local, JMethodID>,
    {
        // Runtime check that the 'local reference lifetime will be tied to
        // Env lifetime for the top JNI stack frame
        self.assert_top();
        use super::signature::Primitive::{
            Boolean, Byte, Char, Double, Float, Int, Long, Short, Void,
        };
        use JavaType::{Array, Object, Primitive};

        let method_id = method_id.lookup(self)?.as_ref().into_raw();
        let class = class.lookup(self)?;

        let obj = obj.as_ref().as_raw();
        let class_raw = class.as_ref().as_raw();

        let jni_args = args.as_ptr();

        macro_rules! invoke {
            ($call:ident -> $ret:ty) => {{
                let o: $ret = jni_call_post_check_ex!(
                    self, v1_1, $call, obj, class_raw, method_id, jni_args
                )?;
                o
            }};
        }

        // Safety: we're sure we're calling the correct JNI method based on `ret_ty` type
        let ret = unsafe {
            match ret_ty {
                Object | Array => {
                    let obj = invoke!(CallNonvirtualObjectMethodA -> jobject);
                    let obj = JObject::from_raw(self, obj);
                    JValueOwned::from(obj)
                }
                Primitive(Boolean) => invoke!(CallNonvirtualBooleanMethodA -> bool).into(),
                Primitive(Char) => invoke!(CallNonvirtualCharMethodA -> u16).into(),
                Primitive(Byte) => invoke!(CallNonvirtualByteMethodA -> i8).into(),
                Primitive(Short) => invoke!(CallNonvirtualShortMethodA -> i16).into(),
                Primitive(Int) => invoke!(CallNonvirtualIntMethodA -> i32).into(),
                Primitive(Long) => invoke!(CallNonvirtualLongMethodA -> i64).into(),
                Primitive(Float) => invoke!(CallNonvirtualFloatMethodA -> f32).into(),
                Primitive(Double) => invoke!(CallNonvirtualDoubleMethodA -> f64).into(),
                Primitive(Void) => {
                    jni_call_post_check_ex!(
                        self,
                        v1_1,
                        CallNonvirtualVoidMethodA,
                        obj,
                        class_raw,
                        method_id,
                        jni_args
                    )?;
                    JValueOwned::Void
                }
            }
        };

        Ok(ret)
    }

    /// Calls an object method safely. This comes with a number of lookups/checks. It
    ///
    /// * Looks up the [JClass] for the given object.
    /// * Looks up the [JMethodID] for the object's class/name/signature combination
    /// * Ensures that the number/types of args matches the signature
    /// * Calls [`Self::call_method_unchecked`] with the verified safe arguments.
    ///
    /// Note: this may cause a Java exception if the arguments are the wrong type, in addition to if the method itself
    /// throws.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use jni::{jni_sig, jni_str, errors::Result, Env, objects::JObject, JValue};
    /// # fn example<'local>(env: &mut Env<'local>, obj: &JObject<'local>) -> Result<()> {
    /// // Call a method with signature: String concat(String str)
    /// let arg = env.new_string("world")?;
    /// let result = env.call_method(
    ///     obj,
    ///     jni_str!("concat"),
    ///     jni_sig!((str: JString) -> JString),
    ///     &[JValue::Object(&arg)],
    /// )?;
    /// # Ok(())
    /// # }
    /// ```
    /// Note: a traditional, raw JNI signature like `"(Ljava/lang/String;)Ljava/lang/String;"` can also be used with
    /// [`jni_sig!`] but this demonstrates the more ergonomic syntax that the macro allows. See the [`jni_sig!`] macro
    /// documentation for more details and examples.
    pub fn call_method<'other_local, 'sig, 'sig_args, O, N, S>(
        &mut self,
        obj: O,
        name: N,
        sig: S,
        args: &[JValue],
    ) -> Result<JValueOwned<'local>>
    where
        O: AsRef<JObject<'other_local>>,
        N: AsRef<JNIStr>,
        S: AsRef<MethodSignature<'sig, 'sig_args>>,
    {
        // Runtime check that the 'local reference lifetime will be tied to
        // Env lifetime for the top JNI stack frame
        self.assert_top();
        let obj = obj.as_ref();
        let obj = null_check!(obj, "call_method obj argument")?;
        let sig = sig.as_ref();

        if sig.args().len() != args.len() {
            return Err(Error::InvalidArgList(sig.into()));
        }

        // check arguments types
        let base_types_match = sig
            .args()
            .iter()
            .zip(args.iter())
            .all(|(exp, act)| match exp {
                JavaType::Primitive(p) => act.primitive_type() == Some(*p),
                JavaType::Object | JavaType::Array => act.primitive_type().is_none(),
            });
        if !base_types_match {
            return Err(Error::InvalidArgList(sig.into()));
        }

        let class = self.get_object_class(obj)?.auto();

        let args: Vec<jvalue> = args.iter().map(|v| v.as_jni()).collect();

        // SAFETY: We've ensured that the Desc trait will be used to dynamically look up a valid
        // method ID for the object's class, method name, and signature (or else it will return an
        // Err). We've also validated the argument counts and types using the same type signature we
        // fetched the original method ID from.
        unsafe { self.call_method_unchecked(obj, (&class, name, sig), sig.ret(), &args) }
    }

    /// Calls a static method safely. This comes with a number of
    /// lookups/checks. It
    ///
    /// * Looks up the [JMethodID] for the class/name/signature combination
    /// * Ensures that the number/types of args matches the signature
    ///   * Cannot check an object's type - but primitive types are matched against each other (including Object)
    /// * Calls [`Self::call_static_method_unchecked`] with the verified safe arguments.
    ///
    /// Note: this may cause a Java exception if the arguments are the wrong
    /// type, in addition to if the method itself throws.
    pub fn call_static_method<'other_local, 'sig, 'sig_args, C, N, S>(
        &mut self,
        class: C,
        name: N,
        sig: S,
        args: &[JValue],
    ) -> Result<JValueOwned<'local>>
    where
        C: Desc<'local, JClass<'other_local>>,
        N: AsRef<JNIStr>,
        S: AsRef<MethodSignature<'sig, 'sig_args>>,
    {
        // Runtime check that the 'local reference lifetime will be tied to
        // Env lifetime for the top JNI stack frame
        self.assert_top();
        let sig = sig.as_ref();
        if sig.args().len() != args.len() {
            return Err(Error::InvalidArgList(sig.into()));
        }

        // check arguments types
        let base_types_match = sig
            .args()
            .iter()
            .zip(args.iter())
            .all(|(exp, act)| match exp {
                JavaType::Primitive(p) => act.primitive_type() == Some(*p),
                JavaType::Object | JavaType::Array => act.primitive_type().is_none(),
            });
        if !base_types_match {
            return Err(Error::InvalidArgList(sig.into()));
        }

        // go ahead and look up the class since we'll need that for the next call.
        let class = class.lookup(self)?;
        let class = class.as_ref();

        let args: Vec<jvalue> = args.iter().map(|v| v.as_jni()).collect();

        // SAFETY: We've obtained the method_id above, so it is valid for this class.
        // We've also validated the argument counts and types using the same type signature
        // we fetched the original method ID from.
        unsafe { self.call_static_method_unchecked(class, (class, name, sig), sig.ret(), &args) }
    }

    /// Calls a non-virtual method safely. This comes with a number of
    /// lookups/checks. It
    ///
    /// * Looks up the [JMethodID] for the class/name/signature combination
    /// * Ensures that the number/types of args matches the signature
    ///   * Cannot check an object's type - but primitive types are matched against each other (including Object)
    /// * Calls [`Self::call_nonvirtual_method_unchecked`] with the verified safe arguments.
    ///
    /// Note: this may cause a Java exception if the arguments are the wrong
    /// type, in addition to if the method itself throws.
    pub fn call_nonvirtual_method<'other_local, 'sig, 'sig_args, O, C, N, S>(
        &mut self,
        obj: O,
        class: C,
        name: N,
        sig: S,
        args: &[JValue],
    ) -> Result<JValueOwned<'local>>
    where
        O: AsRef<JObject<'other_local>>,
        C: Desc<'local, JClass<'other_local>>,
        N: AsRef<JNIStr>,
        S: AsRef<MethodSignature<'sig, 'sig_args>>,
    {
        // Runtime check that the 'local reference lifetime will be tied to
        // Env lifetime for the top JNI stack frame
        self.assert_top();
        let obj = obj.as_ref();
        let obj = null_check!(obj, "call_method obj argument")?;
        let sig = sig.as_ref();
        if sig.args().len() != args.len() {
            return Err(Error::InvalidArgList(sig.into()));
        }

        // check arguments types
        let base_types_match = sig
            .args()
            .iter()
            .zip(args.iter())
            .all(|(exp, act)| match exp {
                JavaType::Primitive(p) => act.primitive_type() == Some(*p),
                JavaType::Object | JavaType::Array => act.primitive_type().is_none(),
            });
        if !base_types_match {
            return Err(Error::InvalidArgList(sig.into()));
        }

        // go ahead and look up the class since we'll need that for the next call.
        let class = class.lookup(self)?;
        let class = class.as_ref();

        let args: Vec<jvalue> = args.iter().map(|v| v.as_jni()).collect();

        // SAFETY: We've obtained the method_id above, so it is valid for this class.
        // We've also validated the argument counts and types using the same type signature
        // we fetched the original method ID from.
        unsafe {
            self.call_nonvirtual_method_unchecked(obj, class, (class, name, sig), sig.ret(), &args)
        }
    }

    /// Create a new object using a constructor. This is done safely using
    /// checks similar to those in `call_static_method`.
    pub fn new_object<'other_local, 'sig, 'sig_args, C, S>(
        &mut self,
        class: C,
        ctor_sig: S,
        ctor_args: &[JValue],
    ) -> Result<JObject<'local>>
    where
        C: Desc<'local, JClass<'other_local>>,
        S: AsRef<MethodSignature<'sig, 'sig_args>>,
    {
        // Runtime check that the 'local reference lifetime will be tied to
        // Env lifetime for the top JNI stack frame
        self.assert_top();
        let ctor_sig = ctor_sig.as_ref();

        // check arguments length
        if ctor_sig.args().len() != ctor_args.len() {
            return Err(Error::InvalidArgList(ctor_sig.into()));
        }

        // check arguments types
        let base_types_match = ctor_sig
            .args()
            .iter()
            .zip(ctor_args.iter())
            .all(|(exp, act)| match exp {
                JavaType::Primitive(p) => act.primitive_type() == Some(*p),
                JavaType::Object | JavaType::Array => act.primitive_type().is_none(),
            });
        if !base_types_match {
            return Err(Error::InvalidArgList(ctor_sig.into()));
        }

        // check return value
        if ctor_sig.ret() != ReturnType::Primitive(Primitive::Void) {
            return Err(Error::InvalidCtorReturn);
        }

        // build strings
        let class = class.lookup(self)?;
        let class = class.as_ref();

        let method_id: JMethodID = Desc::<JMethodID>::lookup((class, ctor_sig), self)?;

        let ctor_args: Vec<jvalue> = ctor_args.iter().map(|v| v.as_jni()).collect();
        // SAFETY: We've obtained the method_id above, so it is valid for this class.
        // We've also validated the argument counts and types using the same type signature
        // we fetched the original method ID from.
        unsafe { self.new_object_unchecked(class, method_id, &ctor_args) }
    }

    /// Create a new object using a constructor. Arguments aren't checked
    /// because of the `JMethodID` usage.
    ///
    /// # Safety
    ///
    /// The provided JMethodID must be valid, and match the types and number of arguments, as well as return type
    /// (always an Object for a constructor). If these are incorrect, the JVM may crash.  The JMethodID must also match
    /// the passed type.
    pub unsafe fn new_object_unchecked<'other_local, C, M>(
        &mut self,
        class: C,
        ctor_id: M,
        ctor_args: &[jvalue],
    ) -> Result<JObject<'local>>
    where
        C: Desc<'local, JClass<'other_local>>,
        M: Desc<'local, JMethodID>,
    {
        // Runtime check that the 'local reference lifetime will be tied to
        // Env lifetime for the top JNI stack frame
        self.assert_top();
        let class = class.lookup(self)?;

        let ctor_id: JMethodID = *ctor_id.lookup(self)?.as_ref();

        let jni_args = ctor_args.as_ptr();

        let obj = unsafe {
            jni_call_post_check_ex_and_null_ret!(
                self,
                v1_1,
                NewObjectA,
                class.as_ref().as_raw(),
                ctor_id.into_raw(),
                jni_args
            )
            .map(|obj| JObject::from_raw(self, obj))
        }?;

        // Ensure that `class` isn't dropped before the JNI call returns.
        drop(class);

        Ok(obj)
    }

    /// Cast a [JObject] to a [JList].
    ///
    /// Returns `Error::WrongObjectType` if the object is not a `java.util.List`.
    #[deprecated(
        since = "0.22.0",
        note = "use JList::cast_local instead or Env::new_cast_local_ref/cast_local/as_cast_local or Env::new_cast_global_ref/cast_global/as_cast_global"
    )]
    pub fn get_list<'any_local>(
        &mut self,
        obj: impl Reference + Into<JObject<'any_local>> + AsRef<JObject<'any_local>>,
    ) -> Result<JList<'any_local>> {
        JList::cast_local(self, obj)
    }

    /// Cast a [JObject] to a [JMap].
    ///
    /// Returns `Error::WrongObjectType` if the object is not a `java.util.Map`.
    #[deprecated(
        since = "0.22.0",
        note = "use JMap::cast_local instead or Env::new_cast_local_ref/cast_local/as_cast_local or Env::new_cast_global_ref/cast_global/as_cast_global"
    )]
    pub fn get_map<'any_local>(
        &mut self,
        obj: impl Reference + Into<JObject<'any_local>> + AsRef<JObject<'any_local>>,
    ) -> Result<JMap<'any_local>> {
        JMap::cast_local(self, obj)
    }

    /// Gets the contents of a Java string, in [modified UTF-8] encoding.
    ///
    /// The returned [MUTF8Chars] can be used to access the modified UTF-8 bytes,
    /// or to convert to a Rust string (which uses standard UTF-8 encoding).
    ///
    /// This entails calling the JNI function `GetStringUTFChars`.
    ///
    /// [modified UTF-8]: https://en.wikipedia.org/wiki/UTF-8#Modified_UTF-8
    ///
    /// # Errors
    ///
    /// Returns an error if `obj` is `null`.
    #[deprecated(
        since = "0.22.0",
        note = "use JString::mutf8_chars or JString::to_string instead; this method is redundant and does not perform unsafe operations"
    )]
    pub fn get_string_unchecked<'any_local, StringRef>(
        &mut self,
        obj: StringRef,
    ) -> Result<MUTF8Chars<'any_local, StringRef>>
    where
        StringRef: AsRef<JString<'any_local>> + Reference,
    {
        MUTF8Chars::from_get_string_utf_chars(self, obj)
    }

    /// Gets the contents of a Java string, in [modified UTF-8] encoding.
    ///
    /// The returned [MUTF8Chars] can be used to access the modified UTF-8 bytes,
    /// or to convert to a Rust string (which uses standard UTF-8 encoding).
    ///
    /// This entails calling the JNI function `GetStringUTFChars`.
    ///
    /// [modified UTF-8]: https://en.wikipedia.org/wiki/UTF-8#Modified_UTF-8
    ///
    /// # Errors
    ///
    /// Returns an error if `obj` is `null`.
    #[deprecated(
        since = "0.22.0",
        note = "use JString::mutf8_chars or JString::to_string instead"
    )]
    pub fn get_string<'any_local, StringRef>(
        &self,
        obj: StringRef,
    ) -> Result<MUTF8Chars<'any_local, StringRef>>
    where
        StringRef: AsRef<JString<'any_local>> + Reference,
    {
        MUTF8Chars::from_get_string_utf_chars(self, obj)
    }

    /// Create a new java string object from a rust string.
    ///
    /// This requires a re-encoding of rusts UTF-8 strings to JNI's modified UTF-8 format before
    /// calling the JNI function `NewStringUTF`.
    ///
    /// To avoid this intermediate copy + encoding, consider using [`JString::from_jni_str`], and
    /// using the [`crate::jni_str`] macro to encode string literals at compile time.
    pub fn new_string(&mut self, from: impl AsRef<str>) -> Result<JString<'local>> {
        JString::new(self, from)
    }

    /// Get the length of a [`JPrimitiveArray`] or [`JObjectArray`].
    #[deprecated(
        since = "0.22.0",
        note = "use JPrimitiveArray::len or JObjectArray::len instead. This method will be removed in a future version"
    )]
    pub fn get_array_length<'other_local, 'array>(
        &self,
        array: &'array impl AsJArrayRaw<'other_local>,
    ) -> Result<jsize> {
        let array = null_check!(array.as_jarray_raw(), "get_array_length array argument")?;
        let len: jsize = unsafe { jni_call_no_post_check_ex!(self, v1_1, GetArrayLength, array)? };
        Ok(len)
    }

    /// Construct a new array holding objects in class `element_class`.
    ///
    /// All elements are initially set to `initial_element`.
    ///
    /// It's recommended to use [JObjectArray::new] or [`Self::new_object_type_array`]
    /// instead, which both support element type parameterization.
    ///
    /// This API may be deprecated and removed in a future version.
    pub fn new_object_array<'other_local_1, 'other_local_2, T, U>(
        &mut self,
        length: jsize,
        element_class: T,
        initial_element: U,
    ) -> Result<JObjectArray<'local>>
    where
        T: Desc<'local, JClass<'other_local_2>>,
        U: AsRef<JObject<'other_local_1>>,
    {
        // Runtime check that the 'local reference lifetime will be tied to
        // Env lifetime for the top JNI stack frame
        self.assert_top();
        let class = element_class.lookup(self)?;

        let array = unsafe {
            jni_call_post_check_ex_and_null_ret!(
                self,
                v1_1,
                NewObjectArray,
                length,
                class.as_ref().as_raw(),
                initial_element.as_ref().as_raw()
            )
            .map(|array| JObjectArray::<JObject>::from_raw(self, array))?
        };

        // Ensure that `class` isn't dropped before the JNI call returns.
        drop(class);

        Ok(array)
    }

    /// Construct a new array holding objects with of type `E`.
    ///
    /// All elements are initially set to `initial_element`.
    ///
    /// It's recommended to use [JObjectArray::new] instead.
    pub fn new_object_type_array<'any_local, E>(
        &mut self,
        length: usize,
        initial_element: impl AsRef<E::Kind<'any_local>>,
    ) -> Result<JObjectArray<'local, E::Kind<'local>>>
    where
        E: Reference,
    {
        JObjectArray::<E>::new(self, length, initial_element)
    }

    /// Returns a local reference to an element of the [`JObjectArray`] `array`.
    #[deprecated(
        since = "0.22.0",
        note = "use JObjectArray::get_element instead. This method will be removed in a future version"
    )]
    pub fn get_object_array_element<'other_local, E: Reference + 'other_local>(
        &mut self,
        array: impl AsRef<JObjectArray<'other_local, E>>,
        index: usize,
    ) -> Result<E::Kind<'local>> {
        array.as_ref().get_element(self, index)
    }

    /// Sets an element of the [`JObjectArray`] `array`.
    #[deprecated(
        since = "0.22.0",
        note = "use JObjectArray::set_element instead. This method will be removed in a future version"
    )]
    pub fn set_object_array_element<'any_local_1, 'any_local_2, E: Reference + 'any_local_1>(
        &self,
        array: impl AsRef<JObjectArray<'any_local_1, E>>,
        index: usize,
        value: impl AsRef<E::Kind<'any_local_2>>,
    ) -> Result<()> {
        array.as_ref().set_element(self, index, value)
    }

    /// Create a new java byte array from a rust byte slice.
    pub fn byte_array_from_slice(&mut self, buf: &[u8]) -> Result<JByteArray<'local>> {
        let bytes = JByteArray::new(self, buf.len())?;
        // SAFETY: i8 and u8 are both plain, single-byte, data types with the same size and
        // alignment.
        //
        // We just want to forward the bitwise representation of the slice and it doesn't matter
        // whether we interpret the data as signed or unsigned.
        let buf: &[i8] = unsafe { std::mem::transmute(buf) };
        bytes.set_region(self, 0, buf)?;
        Ok(bytes)
    }

    /// Converts a java byte array to a rust vector of bytes.
    ///
    /// Returns [Error::IndexOutOfBounds] if one of the calculated indexes in the region is not
    /// valid (in case the array length is changed concurrently).
    ///
    /// This API catches exceptions internally and is not expected to return [`Error::JavaException`]
    pub fn convert_byte_array<'other_local>(
        &self,
        array: impl AsRef<JByteArray<'other_local>>,
    ) -> Result<Vec<u8>> {
        let array = array.as_ref().as_raw();
        let array = null_check!(array, "convert_byte_array array argument")?;

        // GetArrayLength is not documented to throw any exceptions
        let length = unsafe { jni_call_no_post_check_ex!(self, v1_1, GetArrayLength, array)? };
        let mut vec = vec![0u8; length as usize];
        unsafe {
            jni_call_with_catch!(
                catch |env| {
                    crate::exceptions::JArrayIndexOutOfBoundsException =>
                        Err(Error::IndexOutOfBounds),
                    else => Err(Error::JniCall(JniError::Unknown)),
                },
                self,
                v1_1,
                GetByteArrayRegion,
                array,
                0,
                length,
                vec.as_mut_ptr() as *mut i8
            )?;
        }
        Ok(vec)
    }

    /// Create a new [JBooleanArray] of supplied length.
    ///
    /// It is recommended to use [JBooleanArray::new] instead.
    ///
    /// This API may be deprecated and removed in a future version.
    pub fn new_boolean_array(&mut self, length: usize) -> Result<JBooleanArray<'local>> {
        JBooleanArray::new(self, length)
    }

    /// Create a new [JByteArray] of supplied length.
    ///
    /// It is recommended to use [JByteArray::new] instead.
    ///
    /// This API may be deprecated and removed in a future version.
    pub fn new_byte_array(&mut self, length: usize) -> Result<JByteArray<'local>> {
        JByteArray::new(self, length)
    }

    /// Create a new [JCharArray] of supplied length.
    ///
    /// It is recommended to use [JCharArray::new] instead.
    ///
    /// This API may be deprecated and removed in a future version.
    pub fn new_char_array(&mut self, length: usize) -> Result<JCharArray<'local>> {
        JCharArray::new(self, length)
    }

    /// Create a new [JShortArray] of supplied length.
    ///
    /// It is recommended to use [JShortArray::new] instead.
    ///
    /// This API may be deprecated and removed in a future version.
    pub fn new_short_array(&mut self, length: usize) -> Result<JShortArray<'local>> {
        JShortArray::new(self, length)
    }

    /// Create a new [JIntArray] of supplied length.
    ///
    /// It is recommended to use [JIntArray::new] instead.
    ///
    /// This API may be deprecated and removed in a future version.
    pub fn new_int_array(&mut self, length: usize) -> Result<JIntArray<'local>> {
        JIntArray::new(self, length)
    }

    /// Create a new [JLongArray] of supplied length.
    ///
    /// It is recommended to use [JLongArray::new] instead.
    ///
    /// This API may be deprecated and removed in a future version.
    pub fn new_long_array(&mut self, length: usize) -> Result<JLongArray<'local>> {
        JLongArray::new(self, length)
    }

    /// Create a new [JFloatArray] of supplied length.
    ///
    /// It is recommended to use [JFloatArray::new] instead.
    ///
    /// This API may be deprecated and removed in a future version.
    pub fn new_float_array(&mut self, length: usize) -> Result<JFloatArray<'local>> {
        JFloatArray::new(self, length)
    }

    /// Create a new [JDoubleArray] of supplied length.
    ///
    /// It is recommended to use [JDoubleArray::new] instead.
    ///
    /// This API may be deprecated and removed in a future version.
    pub fn new_double_array(&mut self, length: usize) -> Result<JDoubleArray<'local>> {
        JDoubleArray::new(self, length)
    }

    /// Copy elements of the java boolean array from the `start` index to the
    /// `buf` slice. The number of copied elements is equal to the `buf` length.
    ///
    /// # Errors
    /// If `start` is negative _or_ `start + buf.len()` is greater than [`array.length`]
    /// then no elements are copied, an `ArrayIndexOutOfBoundsException` is thrown,
    /// and `Err` is returned.
    ///
    /// [`array.length`]: struct.Env.html#method.get_array_length
    #[deprecated(
        since = "0.22.0",
        note = "use JBooleanArray::get_region instead; this method will be removed in a future version"
    )]
    pub fn get_boolean_array_region<'other_local>(
        &self,
        array: impl AsRef<JBooleanArray<'other_local>>,
        start: jsize,
        buf: &mut [jboolean],
    ) -> Result<()> {
        unsafe {
            <jboolean as TypeArraySealed>::get_region(self, array.as_ref().as_raw(), start, buf)
        }
    }

    /// Copy elements of the java byte array from the `start` index to the `buf`
    /// slice. The number of copied elements is equal to the `buf` length.
    ///
    /// # Errors
    /// If `start` is negative _or_ `start + buf.len()` is greater than [`array.length`]
    /// then no elements are copied, an `ArrayIndexOutOfBoundsException` is thrown,
    /// and `Err` is returned.
    ///
    /// [`array.length`]: struct.Env.html#method.get_array_length
    #[deprecated(
        since = "0.22.0",
        note = "use JByteArray::get_region instead; this method will be removed in a future version"
    )]
    pub fn get_byte_array_region<'other_local>(
        &self,
        array: impl AsRef<JByteArray<'other_local>>,
        start: jsize,
        buf: &mut [jbyte],
    ) -> Result<()> {
        unsafe { <jbyte as TypeArraySealed>::get_region(self, array.as_ref().as_raw(), start, buf) }
    }

    /// Copy elements of the java char array from the `start` index to the
    /// `buf` slice. The number of copied elements is equal to the `buf` length.
    ///
    /// # Errors
    /// If `start` is negative _or_ `start + buf.len()` is greater than [`array.length`]
    /// then no elements are copied, an `ArrayIndexOutOfBoundsException` is thrown,
    /// and `Err` is returned.
    ///
    /// [`array.length`]: struct.Env.html#method.get_array_length
    #[deprecated(
        since = "0.22.0",
        note = "use JCharArray::get_region instead; this method will be removed in a future version"
    )]
    pub fn get_char_array_region<'other_local>(
        &self,
        array: impl AsRef<JCharArray<'other_local>>,
        start: jsize,
        buf: &mut [jchar],
    ) -> Result<()> {
        unsafe { <jchar as TypeArraySealed>::get_region(self, array.as_ref().as_raw(), start, buf) }
    }

    /// Copy elements of the java short array from the `start` index to the
    /// `buf` slice. The number of copied elements is equal to the `buf` length.
    ///
    /// # Errors
    /// If `start` is negative _or_ `start + buf.len()` is greater than [`array.length`]
    /// then no elements are copied, an `ArrayIndexOutOfBoundsException` is thrown,
    /// and `Err` is returned.
    ///
    /// [`array.length`]: struct.Env.html#method.get_array_length
    #[deprecated(
        since = "0.22.0",
        note = "use JShortArray::get_region instead; this method will be removed in a future version"
    )]
    pub fn get_short_array_region<'other_local>(
        &self,
        array: impl AsRef<JShortArray<'other_local>>,
        start: jsize,
        buf: &mut [jshort],
    ) -> Result<()> {
        unsafe {
            <jshort as TypeArraySealed>::get_region(self, array.as_ref().as_raw(), start, buf)
        }
    }

    /// Copy elements of the java int array from the `start` index to the
    /// `buf` slice. The number of copied elements is equal to the `buf` length.
    ///
    /// # Errors
    /// If `start` is negative _or_ `start + buf.len()` is greater than [`array.length`]
    /// then no elements are copied, an `ArrayIndexOutOfBoundsException` is thrown,
    /// and `Err` is returned.
    ///
    /// [`array.length`]: struct.Env.html#method.get_array_length
    #[deprecated(
        since = "0.22.0",
        note = "use JIntArray::get_region instead; this method will be removed in a future version"
    )]
    pub fn get_int_array_region<'other_local>(
        &self,
        array: impl AsRef<JIntArray<'other_local>>,
        start: jsize,
        buf: &mut [jint],
    ) -> Result<()> {
        unsafe { <jint as TypeArraySealed>::get_region(self, array.as_ref().as_raw(), start, buf) }
    }

    /// Copy elements of the java long array from the `start` index to the
    /// `buf` slice. The number of copied elements is equal to the `buf` length.
    ///
    /// # Errors
    /// If `start` is negative _or_ `start + buf.len()` is greater than [`array.length`]
    /// then no elements are copied, an `ArrayIndexOutOfBoundsException` is thrown,
    /// and `Err` is returned.
    ///
    /// [`array.length`]: struct.Env.html#method.get_array_length
    #[deprecated(
        since = "0.22.0",
        note = "use JLongArray::get_region instead; this method will be removed in a future version"
    )]
    pub fn get_long_array_region<'other_local>(
        &self,
        array: impl AsRef<JLongArray<'other_local>>,
        start: jsize,
        buf: &mut [jlong],
    ) -> Result<()> {
        unsafe { <jlong as TypeArraySealed>::get_region(self, array.as_ref().as_raw(), start, buf) }
    }

    /// Copy elements of the java float array from the `start` index to the
    /// `buf` slice. The number of copied elements is equal to the `buf` length.
    ///
    /// # Errors
    /// If `start` is negative _or_ `start + buf.len()` is greater than [`array.length`]
    /// then no elements are copied, an `ArrayIndexOutOfBoundsException` is thrown,
    /// and `Err` is returned.
    ///
    /// [`array.length`]: struct.Env.html#method.get_array_length
    #[deprecated(
        since = "0.22.0",
        note = "use JFloatArray::get_region instead; this method will be removed in a future version"
    )]
    pub fn get_float_array_region<'other_local>(
        &self,
        array: impl AsRef<JFloatArray<'other_local>>,
        start: jsize,
        buf: &mut [jfloat],
    ) -> Result<()> {
        unsafe {
            <jfloat as TypeArraySealed>::get_region(self, array.as_ref().as_raw(), start, buf)
        }
    }

    /// Copy elements of the java double array from the `start` index to the
    /// `buf` slice. The number of copied elements is equal to the `buf` length.
    ///
    /// # Errors
    /// If `start` is negative _or_ `start + buf.len()` is greater than [`array.length`]
    /// then no elements are copied, an `ArrayIndexOutOfBoundsException` is thrown,
    /// and `Err` is returned.
    ///
    /// [`array.length`]: struct.Env.html#method.get_array_length
    #[deprecated(
        since = "0.22.0",
        note = "use JDoubleArray::get_region instead; this method will be removed in a future version"
    )]
    pub fn get_double_array_region<'other_local>(
        &self,
        array: impl AsRef<JDoubleArray<'other_local>>,
        start: jsize,
        buf: &mut [jdouble],
    ) -> Result<()> {
        unsafe {
            <jdouble as TypeArraySealed>::get_region(self, array.as_ref().as_raw(), start, buf)
        }
    }

    /// Copy the contents of the `buf` slice to the java boolean array at the
    /// `start` index.
    #[deprecated(
        since = "0.22.0",
        note = "use JBooleanArray::set_region instead; this method will be removed in a future version"
    )]
    pub fn set_boolean_array_region<'other_local>(
        &self,
        array: impl AsRef<JBooleanArray<'other_local>>,
        start: jsize,
        buf: &[jboolean],
    ) -> Result<()> {
        unsafe {
            <jboolean as TypeArraySealed>::set_region(self, array.as_ref().as_raw(), start, buf)
        }
    }

    /// Copy the contents of the `buf` slice to the java byte array at the
    /// `start` index.
    #[deprecated(
        since = "0.22.0",
        note = "use JByteArray::set_region instead; this method will be removed in a future version"
    )]
    pub fn set_byte_array_region<'other_local>(
        &self,
        array: impl AsRef<JByteArray<'other_local>>,
        start: jsize,
        buf: &[jbyte],
    ) -> Result<()> {
        unsafe { <jbyte as TypeArraySealed>::set_region(self, array.as_ref().as_raw(), start, buf) }
    }

    /// Copy the contents of the `buf` slice to the java char array at the
    /// `start` index.
    #[deprecated(
        since = "0.22.0",
        note = "use JCharArray::set_region instead; this method will be removed in a future version"
    )]
    pub fn set_char_array_region<'other_local>(
        &self,
        array: impl AsRef<JCharArray<'other_local>>,
        start: jsize,
        buf: &[jchar],
    ) -> Result<()> {
        unsafe { <jchar as TypeArraySealed>::set_region(self, array.as_ref().as_raw(), start, buf) }
    }

    /// Copy the contents of the `buf` slice to the java short array at the
    /// `start` index.
    #[deprecated(
        since = "0.22.0",
        note = "use JShortArray::set_region instead; this method will be removed in a future version"
    )]
    pub fn set_short_array_region<'other_local>(
        &self,
        array: impl AsRef<JShortArray<'other_local>>,
        start: jsize,
        buf: &[jshort],
    ) -> Result<()> {
        unsafe {
            <jshort as TypeArraySealed>::set_region(self, array.as_ref().as_raw(), start, buf)
        }
    }

    /// Copy the contents of the `buf` slice to the java int array at the
    /// `start` index.
    #[deprecated(
        since = "0.22.0",
        note = "use JIntArray::set_region instead; this method will be removed in a future version"
    )]
    pub fn set_int_array_region<'other_local>(
        &self,
        array: impl AsRef<JIntArray<'other_local>>,
        start: jsize,
        buf: &[jint],
    ) -> Result<()> {
        unsafe { <jint as TypeArraySealed>::set_region(self, array.as_ref().as_raw(), start, buf) }
    }

    /// Copy the contents of the `buf` slice to the java long array at the
    /// `start` index.
    #[deprecated(
        since = "0.22.0",
        note = "use JLongArray::set_region instead; this method will be removed in a future version"
    )]
    pub fn set_long_array_region<'other_local>(
        &self,
        array: impl AsRef<JLongArray<'other_local>>,
        start: jsize,
        buf: &[jlong],
    ) -> Result<()> {
        unsafe { <jlong as TypeArraySealed>::set_region(self, array.as_ref().as_raw(), start, buf) }
    }

    /// Copy the contents of the `buf` slice to the java float array at the
    /// `start` index.
    #[deprecated(
        since = "0.22.0",
        note = "use JFloatArray::set_region instead; this method will be removed in a future version"
    )]
    pub fn set_float_array_region<'other_local>(
        &self,
        array: impl AsRef<JFloatArray<'other_local>>,
        start: jsize,
        buf: &[jfloat],
    ) -> Result<()> {
        unsafe {
            <jfloat as TypeArraySealed>::set_region(self, array.as_ref().as_raw(), start, buf)
        }
    }

    /// Copy the contents of the `buf` slice to the java double array at the
    /// `start` index.
    #[deprecated(
        since = "0.22.0",
        note = "use JDoubleArray::set_region instead; this method will be removed in a future version"
    )]
    pub fn set_double_array_region<'other_local>(
        &self,
        array: impl AsRef<JDoubleArray<'other_local>>,
        start: jsize,
        buf: &[jdouble],
    ) -> Result<()> {
        unsafe {
            <jdouble as TypeArraySealed>::set_region(self, array.as_ref().as_raw(), start, buf)
        }
    }

    /// Convert a [`JMethodID`] into a [`JObject`] with the corresponding
    /// `java.lang.reflect.Method` or `java.lang.reflect.Constructor` instance.
    pub fn to_reflected_method<'other_local>(
        &mut self,
        class: impl Desc<'local, JClass<'other_local>>,
        method_id: impl Desc<'local, JMethodID>,
    ) -> Result<JObject<'local>> {
        // Safety: Rust type safety ensures that method_id is a JMethodID, while is_static is false
        unsafe { self.to_reflected_method_base(class, method_id, JMethodID::into_raw, false) }
    }

    /// Convert a [`JStaticMethodID`] into a [`JObject`] with the corresponding
    /// `java.lang.reflect.Method` instance.
    pub fn to_reflected_static_method<'other_local>(
        &mut self,
        class: impl Desc<'local, JClass<'other_local>>,
        method_id: impl Desc<'local, JStaticMethodID>,
    ) -> Result<JObject<'local>> {
        // Safety: Rust type safety ensures that method_id is a JStaticMethodID, while is_static is true
        unsafe { self.to_reflected_method_base(class, method_id, JStaticMethodID::into_raw, true) }
    }

    /// Convert a [`JMethodID`] or [`JStaticMethodID`] into a [`JObject`] with the
    /// corresponding `java.lang.reflect.Method` or `java.lang.reflect.Constructor`
    /// instance.
    ///
    /// The `to_jmethodid` function is used to convert the method ID type into
    /// a raw [`sys::jmethodID`].
    ///
    /// # Safety
    ///
    /// `is_static` must correctly indicate whether the method ID is for a static method. (The JNI
    /// spec does not define what happens if this is incorrect.)
    #[allow(clippy::wrong_self_convention)]
    unsafe fn to_reflected_method_base<'other_local, M>(
        &mut self,
        class: impl Desc<'local, JClass<'other_local>>,
        method_id: impl Desc<'local, M>,
        to_jmethodid: impl FnOnce(M) -> crate::sys::jmethodID,
        is_static: bool,
    ) -> Result<JObject<'local>>
    where
        M: Copy,
    {
        // Runtime check that the 'local reference lifetime will be tied to
        // Env lifetime for the top JNI stack frame
        self.assert_top();
        let class = class.lookup(self)?;

        let method_id = to_jmethodid(*method_id.lookup(self)?.as_ref());

        unsafe {
            jni_call_post_check_ex_and_null_ret!(
                self,
                v1_2,
                ToReflectedMethod,
                class.as_ref().as_raw(),
                method_id,
                is_static
            )
            .map(|jobject| JObject::from_raw(self, jobject))
        }
    }

    /// Get a field without checking the provided type against the actual field.
    ///
    /// # Safety
    ///
    /// - The `obj` must not be `null`
    /// - The `field` must be associated with the given `obj` (got from passing the `obj` to [Env::get_field_id])
    /// - The field must have the specified `ty` type.
    pub unsafe fn get_field_unchecked<'other_local, O, F>(
        &mut self,
        obj: O,
        field: F,
        ty: JavaType,
    ) -> Result<JValueOwned<'local>>
    where
        O: AsRef<JObject<'other_local>>,
        F: Desc<'local, JFieldID>,
    {
        // Runtime check that the 'local reference lifetime will be tied to
        // Env lifetime for the top JNI stack frame
        self.assert_top();
        use super::signature::Primitive::{
            Boolean, Byte, Char, Double, Float, Int, Long, Short, Void,
        };
        use JavaType::{Array, Object, Primitive};

        let obj = obj.as_ref();
        let obj = null_check!(obj, "get_field_typed obj argument")?;

        let field = field.lookup(self)?.as_ref().into_raw();
        let obj = obj.as_raw();

        macro_rules! field {
            ($get_field:ident) => {{
                // Safety: No exceptions are defined for Get*Field and we assume
                // the caller knows that the field is valid
                unsafe {
                    JValueOwned::from(jni_call_no_post_check_ex!(
                        self, v1_1, $get_field, obj, field
                    )?)
                }
            }};
        }

        match ty {
            Object | Array => {
                let obj = unsafe {
                    jni_call_post_check_ex!(self, v1_1, GetObjectField, obj, field)
                        .map(|obj| JObject::from_raw(self, obj))?
                };
                Ok(obj.into())
            }
            Primitive(Char) => Ok(field!(GetCharField)),
            Primitive(Boolean) => Ok(field!(GetBooleanField)),
            Primitive(Short) => Ok(field!(GetShortField)),
            Primitive(Int) => Ok(field!(GetIntField)),
            Primitive(Long) => Ok(field!(GetLongField)),
            Primitive(Float) => Ok(field!(GetFloatField)),
            Primitive(Double) => Ok(field!(GetDoubleField)),
            Primitive(Byte) => Ok(field!(GetByteField)),
            Primitive(Void) => Err(Error::WrongJValueType("void", "see java field")),
        }
    }

    /// Set a field without any type checking.
    ///
    /// # Safety
    ///
    /// - The `obj` must not be `null`
    /// - The `field` must be associated with the given `obj` (got from passing the `obj` to [Env::get_field_id])
    /// - The field type must match the given `value` type.
    pub unsafe fn set_field_unchecked<'other_local, O, F>(
        &mut self,
        obj: O,
        field: F,
        value: JValue,
    ) -> Result<()>
    where
        O: AsRef<JObject<'other_local>>,
        F: Desc<'local, JFieldID>,
    {
        if let JValue::Void = value {
            return Err(Error::WrongJValueType("void", "see java field"));
        }

        let obj = obj.as_ref();

        let field = field.lookup(self)?.as_ref().into_raw();
        let obj = obj.as_raw();

        macro_rules! set_field {
            ($set_field:ident($val:expr)) => {{ unsafe { jni_call_no_post_check_ex!(self, v1_1, $set_field, obj, field, $val) } }};
        }

        match value {
            JValue::Object(o) => set_field!(SetObjectField(o.as_raw()))?,
            JValue::Bool(b) => set_field!(SetBooleanField(b))?,
            JValue::Char(c) => set_field!(SetCharField(c))?,
            JValue::Short(s) => set_field!(SetShortField(s))?,
            JValue::Int(i) => set_field!(SetIntField(i))?,
            JValue::Long(l) => set_field!(SetLongField(l))?,
            JValue::Float(f) => set_field!(SetFloatField(f))?,
            JValue::Double(d) => set_field!(SetDoubleField(d))?,
            JValue::Byte(b) => set_field!(SetByteField(b))?,
            _ => (),
        };

        Ok(())
    }

    /// Get a field. Requires an object class lookup and a field id lookup
    /// internally.
    pub fn get_field<'other_local, 'sig, O, N, S>(
        &mut self,
        obj: O,
        name: N,
        sig: S,
    ) -> Result<JValueOwned<'local>>
    where
        O: AsRef<JObject<'other_local>>,
        N: AsRef<JNIStr>,
        S: AsRef<FieldSignature<'sig>>,
    {
        // Runtime check that the 'local reference lifetime will be tied to
        // Env lifetime for the top JNI stack frame
        self.assert_top();
        let obj = obj.as_ref();
        let obj = null_check!(obj, "get_field obj argument")?;
        let class = self.get_object_class(obj)?.auto();

        let sig = sig.as_ref();
        let field_ty = sig.ty();
        let field_id: JFieldID = Desc::<JFieldID>::lookup((&class, name, sig), self)?;

        // Safety: Since we have explicitly looked up the field ID based on the given
        // return type we have already validate that they match
        unsafe { self.get_field_unchecked(obj, field_id, field_ty) }
    }

    /// Set a field. Does the same lookups as `get_field` and ensures that the
    /// type matches the given value.
    pub fn set_field<'other_local, 'sig, O, N, S>(
        &mut self,
        obj: O,
        name: N,
        sig: S,
        value: JValue,
    ) -> Result<()>
    where
        O: AsRef<JObject<'other_local>>,
        N: AsRef<JNIStr>,
        S: AsRef<FieldSignature<'sig>>,
    {
        let obj = obj.as_ref();
        let obj = null_check!(obj, "set_field obj argument")?;
        let sig = sig.as_ref();
        let field_ty = sig.ty();

        if value.java_type() != field_ty {
            return Err(Error::WrongJValueType(value.type_name(), "see java field"));
        }

        let class = self.get_object_class(obj)?.auto();

        // Safety: We have explicitly checked that the field type matches
        // the value type and the field ID is going to be looked up dynamically
        // based on the class, name and signature (so it's safe to use)
        unsafe { self.set_field_unchecked(obj, (&class, name, sig), value) }
    }

    /// Get a static field without checking the provided type against the actual
    /// field.
    ///
    /// # Safety
    ///
    /// - The `class` must not be null
    /// - The `field` must be associated with the given `class` (got from passing the `class` to [Env::get_static_field_id])
    /// - The field must have the specified `ty` type.
    pub unsafe fn get_static_field_unchecked<'other_local, C, F>(
        &mut self,
        class: C,
        field: F,
        ty: JavaType,
    ) -> Result<JValueOwned<'local>>
    where
        C: Desc<'local, JClass<'other_local>>,
        F: Desc<'local, JStaticFieldID>,
    {
        // Runtime check that the 'local reference lifetime will be tied to
        // Env lifetime for the top JNI stack frame
        self.assert_top();
        use super::signature::Primitive::{
            Boolean, Byte, Char, Double, Float, Int, Long, Short, Void,
        };
        use JavaType::{Array, Object, Primitive};

        let class = class.lookup(self)?;
        let field = field.lookup(self)?;

        macro_rules! field {
            ($get_field:ident) => {{
                unsafe {
                    jni_call_post_check_ex!(
                        self,
                        v1_1,
                        $get_field,
                        class.as_ref().as_raw(),
                        field.as_ref().into_raw()
                    )?
                }
            }};
        }

        let ret = match ty {
            Primitive(Void) => Err(Error::WrongJValueType("void", "see java field")),
            Object | Array => {
                let obj = field!(GetStaticObjectField);
                let obj = unsafe { JObject::from_raw(self, obj) };
                Ok(JValueOwned::from(obj))
            }
            Primitive(Boolean) => Ok(field!(GetStaticBooleanField).into()),
            Primitive(Char) => Ok(field!(GetStaticCharField).into()),
            Primitive(Short) => Ok(field!(GetStaticShortField).into()),
            Primitive(Int) => Ok(field!(GetStaticIntField).into()),
            Primitive(Long) => Ok(field!(GetStaticLongField).into()),
            Primitive(Float) => Ok(field!(GetStaticFloatField).into()),
            Primitive(Double) => Ok(field!(GetStaticDoubleField).into()),
            Primitive(Byte) => Ok(field!(GetStaticByteField).into()),
        };

        // Ensure that `class` isn't dropped before the JNI call returns.
        drop(class);

        ret
    }

    /// Set a static field. Requires a class lookup and a field id lookup internally.
    ///
    /// # Safety
    ///
    /// - The `class` must not be null
    /// - The `field` must be associated with the given `class` (got from passing the `class` to [Env::get_static_field_id])
    /// - The field type must match the given `value` type.
    pub unsafe fn set_static_field_unchecked<'other_local, C, F>(
        &mut self,
        class: C,
        field: F,
        value: JValue,
    ) -> Result<()>
    where
        C: Desc<'local, JClass<'other_local>>,
        F: Desc<'local, JStaticFieldID>,
    {
        let class = class.lookup(self)?;
        let field = field.lookup(self)?;

        macro_rules! set_field {
            ($set_field:ident($val:expr)) => {{
                unsafe {
                    jni_call_no_post_check_ex!(
                        self,
                        v1_1,
                        $set_field,
                        class.as_ref().as_raw(),
                        field.as_ref().into_raw(),
                        $val
                    )
                }
            }};
        }

        match value {
            JValue::Object(v) => set_field!(SetStaticObjectField(v.as_raw()))?,
            JValue::Byte(v) => set_field!(SetStaticByteField(v))?,
            JValue::Char(v) => set_field!(SetStaticCharField(v))?,
            JValue::Short(v) => set_field!(SetStaticShortField(v))?,
            JValue::Int(v) => set_field!(SetStaticIntField(v))?,
            JValue::Long(v) => set_field!(SetStaticLongField(v))?,
            JValue::Bool(v) => set_field!(SetStaticBooleanField(v))?,
            JValue::Float(v) => set_field!(SetStaticFloatField(v))?,
            JValue::Double(v) => set_field!(SetStaticDoubleField(v))?,
            _ => (),
        }

        // Ensure that `class` isn't dropped before the JNI call returns.
        drop(class);

        Ok(())
    }

    /// Get a static field. Requires a class lookup and a field id lookup
    /// internally.
    pub fn get_static_field<'other_local, 'sig, C, N, S>(
        &mut self,
        class: C,
        name: N,
        sig: S,
    ) -> Result<JValueOwned<'local>>
    where
        C: Desc<'local, JClass<'other_local>>,
        N: AsRef<JNIStr>,
        S: AsRef<FieldSignature<'sig>>,
    {
        // Runtime check that the 'local reference lifetime will be tied to
        // Env lifetime for the top JNI stack frame
        self.assert_top();
        let sig = sig.as_ref();
        let field_ty = sig.ty();

        // go ahead and look up the class since we'll need that for the next call.
        let class = class.lookup(self)?;

        // SAFETY: We have verified that `class`, `field`, `sig` and `ty` are valid
        unsafe {
            self.get_static_field_unchecked(class.as_ref(), (class.as_ref(), name, sig), field_ty)
        }
    }

    /// Set a static field. Requires a class lookup and a field id lookup internally.
    pub fn set_static_field<'other_local, 'sig, C, N, S>(
        &mut self,
        class: C,
        name: N,
        sig: S,
        value: JValue,
    ) -> Result<()>
    where
        C: Desc<'local, JClass<'other_local>>,
        N: AsRef<JNIStr>,
        S: AsRef<FieldSignature<'sig>>,
    {
        let sig = sig.as_ref();
        let field_ty = sig.ty();

        if value.java_type() != field_ty {
            return Err(Error::WrongJValueType(value.type_name(), "see java field"));
        }

        let class = class.lookup(self)?;

        // Safety: We have explicitly checked that the field type matches the value type.
        unsafe {
            self.set_static_field_unchecked(class.as_ref(), (class.as_ref(), name, sig), value)
        }
    }

    /// Looks up the field ID for the given field name and takes the monitor
    /// lock on the given object so the field can be updated without racing
    /// with other Java threads
    fn lock_rust_field<'other_local, O, S>(
        &self,
        obj: O,
        field: S,
    ) -> Result<(MonitorGuard<'local>, JFieldID)>
    where
        O: AsRef<JObject<'other_local>>,
        S: AsRef<JNIStr>,
    {
        // Note: although the returned Monitor is associated with a lifetime, this API doesn't need
        // a `&mut self` reference because we don't need to create and return a new local reference
        // (Monitors aren't JNI types that are owned by a JNI stack frame).

        // We also don't assert that `self.level == JavaVM::thread_attach_guard_level()` since the
        // returned monitor is associated with the current thread and there's no reason you can't
        // lock with a reference that's not from the top stack frame.

        // Since `Desc::lookup` may need to create a temporary local reference for the object class
        // (which we don't want to leak), we push a new stack frame that we can get a mutable
        // reference for.

        self.with_local_frame(DEFAULT_LOCAL_FRAME_CAPACITY, |env| {
            let obj = obj.as_ref();
            let class = env.get_object_class(obj)?;
            let field_id: JFieldID =
                Desc::<JFieldID>::lookup((&class, &field, jni_sig!("J")), env)?;
            let guard = self.lock_obj(obj)?;
            Ok((guard, field_id))
        })
    }

    /// Surrenders ownership of a Rust value to Java.
    ///
    /// This requires an object with a `long` field to store the pointer.
    ///
    /// In Java the property may look like:
    /// ```java
    /// private long myRustValueHandle = 0;
    /// ```
    ///
    /// Or, in Kotlin the property may look like:
    /// ```java
    /// private var myRustValueHandle: Long = 0
    /// ```
    ///
    /// _Note that `private` properties are accessible to JNI which may be
    /// preferable to avoid exposing the handles to more code than necessary
    /// (since the handles are usually only meaningful to Rust code)_.
    ///
    /// The Rust value will be implicitly wrapped in a `Box<Mutex<T>>`.
    ///
    /// The Java object will be locked while changing the field value.
    ///
    /// # Safety
    ///
    /// This will lead to undefined behaviour if the specified field
    /// doesn't have a type of `long`.
    ///
    /// It's important to note that using this API will leak memory if
    /// [`Self::take_rust_field`] is never called so that the Rust type may be
    /// dropped.
    ///
    /// One suggestion that may help ensure that a set Rust field will be
    /// cleaned up later is for the Java object to implement `Closeable` and let
    /// people use a `use` block (Kotlin) or `try-with-resources` (Java).
    ///
    /// **DO NOT** make a copy of the handle stored in one of these fields
    /// since that could lead to a use-after-free error if the Rust type is
    /// taken and dropped multiple times from Rust. If you need to copy an
    /// object with one of these fields then the field should be zero
    /// initialized in the copy.
    pub unsafe fn set_rust_field<'other_local, O, S, T>(
        &self,
        obj: O,
        field: S,
        rust_object: T,
    ) -> Result<()>
    where
        O: AsRef<JObject<'other_local>>,
        S: AsRef<JNIStr>,
        T: Send + 'static,
    {
        let (_guard, field_id) = self.lock_rust_field(&obj, &field)?;

        // It's OK that we don't push a new stack frame here since we know we are dealing with a
        // `jlong` field and since we have already looked up the field ID then we also know that
        // get_field_unchecked and set_field_unchecked don't need to create any local references.

        self.with_top_local_frame(|env| {
            // Safety: the requirement that the given field must be a `long` is
            // documented in the 'Safety' section of this function
            unsafe {
                let field_ptr = env
                    .get_field_unchecked(&obj, field_id, ReturnType::Primitive(Primitive::Long))?
                    .j()? as *mut Mutex<T>;
                if !field_ptr.is_null() {
                    return Err(Error::FieldAlreadySet(field.as_ref().to_str().into()));
                }
            }

            let mbox = Box::new(::std::sync::Mutex::new(rust_object));
            let ptr: *mut Mutex<T> = Box::into_raw(mbox);

            // Safety: the requirement that the given field must be a `long` is
            // documented in the 'Safety' section of this function
            unsafe { env.set_field_unchecked(obj, field_id, (ptr as crate::sys::jlong).into()) }
        })
    }

    /// Gets a lock on a Rust value that's been given to a Java object.
    ///
    /// Java still retains ownership and [`Self::take_rust_field`] will still
    /// need to be called at some point.
    ///
    /// The Java object will be locked before reading the field value but the
    /// Java object lock will be released after the Rust `Mutex` lock for the
    /// field value has been taken (i.e the Java object won't be locked once
    /// this function returns).
    ///
    /// # Safety
    ///
    /// This will lead to undefined behaviour if the specified field
    /// doesn't have a type of `long`.
    ///
    /// If the field contains a non-zero value then it is assumed to be a valid
    /// pointer that was set via `set_rust_field` and will lead to undefined
    /// behaviour if that is not true.
    pub unsafe fn get_rust_field<'other_local, O, S, T>(
        &self,
        obj: O,
        field: S,
    ) -> Result<MutexGuard<'local, T>>
    where
        O: AsRef<JObject<'other_local>>,
        S: AsRef<JNIStr>,
        T: Send + 'static,
    {
        let (_guard, field_id) = self.lock_rust_field(&obj, &field)?;

        // Reference Leaks:
        //
        // It's ok that we don't push a new stack frame here since we know we are dealing with a
        // `jlong` field and since we have already looked up the field ID then we also know that
        // get_field_unchecked doesn't need to create any local references.

        self.with_top_local_frame(|env| {
            // Safety: the requirement that the given field must be a `long` is
            // documented in the 'Safety' section of this function
            unsafe {
                let field_ptr = env
                    .get_field_unchecked(obj, field_id, ReturnType::Primitive(Primitive::Long))?
                    .j()? as *mut Mutex<T>;
                null_check!(field_ptr, "rust value from Java")?;
                // dereferencing is safe, because we checked it for null
                Ok((*field_ptr).lock().unwrap())
            }
        })
    }

    /// Take a Rust field back from Java.
    ///
    /// It sets the field to a null pointer to signal that it's empty.
    ///
    /// The Java object will be locked before taking the field value.
    ///
    /// # Safety
    ///
    /// This will lead to undefined behaviour if the specified field
    /// doesn't have a type of `long`.
    ///
    /// If the field contains a non-zero value then it is assumed to be a valid
    /// pointer that was set via `set_rust_field` and will lead to undefined
    /// behaviour if that is not true.
    pub unsafe fn take_rust_field<'other_local, O, S, T>(&self, obj: O, field: S) -> Result<T>
    where
        O: AsRef<JObject<'other_local>>,
        S: AsRef<JNIStr>,
        T: Send + 'static,
    {
        let (_guard, field_id) = self.lock_rust_field(&obj, &field)?;

        // Reference Leaks:
        //
        // It's ok that we don't push a new stack frame here since we know we are dealing with a
        // `jlong` field and since we have already looked up the field ID then we also know that
        // get_field_unchecked doesn't need to create any local references.

        self.with_top_local_frame(|env| {
            // Safety: the requirement that the given field must be a `long` is
            // documented in the 'Safety' section of this function
            let mbox = unsafe {
                let ptr = env
                    .get_field_unchecked(&obj, field_id, ReturnType::Primitive(Primitive::Long))?
                    .j()? as *mut Mutex<T>;

                null_check!(ptr, "rust value from Java")?;
                Box::from_raw(ptr)
            };

            // attempt to acquire the lock. This prevents us from consuming the
            // mutex if there's an outstanding lock. No one else will be able to
            // get a new one as long as we're in the guarded scope.
            drop(mbox.try_lock()?);

            // Safety: the requirement that the given field must be a `long` is
            // documented in the 'Safety' section of this function
            unsafe {
                env.set_field_unchecked(obj, field_id, (0 as sys::jlong).into())?;
            }

            Ok(mbox.into_inner().unwrap())
        })
    }

    /// Lock a Java object. The MonitorGuard that this returns is responsible
    /// for ensuring that it gets unlocked.
    pub fn lock_obj<'other_local, O>(&self, obj: O) -> Result<MonitorGuard<'local>>
    where
        O: AsRef<JObject<'other_local>>,
    {
        // Note: although the returned Monitor is associated with a lifetime, we
        // don't need a `&mut self` reference and we don't assert that
        // `self.level == JavaVM::thread_attach_guard_level()` since the
        // returned monitor is associated with the current thread and is not a
        // local reference.

        let inner = obj.as_ref().as_raw();
        let res = unsafe { jni_call_no_post_check_ex!(self, v1_1, MonitorEnter, inner)? };
        jni_error_code_to_result(res)?;

        Ok(MonitorGuard {
            obj: inner,
            life: Default::default(),
        })
    }

    /// Returns the Java VM interface.
    ///
    /// May return [`Error::JavaException`] if called while there is a pending
    /// exception.
    pub fn get_java_vm(&self) -> Result<JavaVM> {
        // This avoids calling JNI if we already know the VM pointer
        JavaVM::from_env(self)
    }

    /// Ensures that at least a given number of local references can be created
    /// in the current thread.
    pub fn ensure_local_capacity(&self, capacity: usize) -> Result<()> {
        let capacity: jint = capacity
            .try_into()
            .map_err(|_| Error::JniCall(JniError::InvalidArguments))?;
        // Safety:
        // - jni-rs required JNI_VERSION > 1.2
        // - we have ensured capacity is >= 0
        // - EnsureLocalCapacity has no documented exceptions that it throws
        let res = unsafe { jni_call_no_post_check_ex!(self, v1_2, EnsureLocalCapacity, capacity)? };
        jni_error_code_to_result(res)?;
        Ok(())
    }

    // FIXME: this API shouldn't need a `&mut self` reference since it doesn't return a local reference
    // (currently it just needs the `&mut self` for the sake of `Desc<JClass>::lookup`)
    //
    /// Bind function pointers to native methods of class according to method name and signature.
    ///
    /// For details see
    /// [documentation](https://docs.oracle.com/javase/8/docs/technotes/guides/jni/spec/functions.html#RegisterNatives).
    ///
    /// # Safety
    ///
    /// The caller must ensure that the function signatures in `methods` have a `this` or `class`
    /// parameter as appropriate for instance or static methods, and that the function pointers are
    /// valid and match the signatures.
    ///
    /// Although `NativeMethod` has an `unsafe` constructor that requires the caller to ensure that
    /// the function pointer is valid and matches the signature, this API is still marked as
    /// `unsafe` to reflect the additional risk that the signature matches but the second parameter
    /// is not consistent with whether the method is static or instance.
    ///
    /// - **Static native methods** must have a `class: JClass<'local>` parameter as the second parameter.
    ///
    /// - **Instance native methods** must have a `this: JObject<'local>` or `this: MyType<'local>` parameter as the second parameter.
    ///
    /// # Throws
    ///
    /// - `NoSuchMethodError` - if a method could not be found (based on its name and signature) or
    ///   it was not a native method.
    ///
    /// **Note** that there is no way for the JVM to report errors if the function pointer is invalid or
    /// does not match the signature, so incorrect function pointers may lead to crashes or
    /// undefined behaviour.
    pub unsafe fn register_native_methods<'other_local, T>(
        &mut self,
        class: T,
        methods: &[NativeMethod],
    ) -> Result<()>
    where
        T: Desc<'local, JClass<'other_local>>,
    {
        let class = class.lookup(self)?;
        // Safety:
        //  - NativeMethod is a #[transparent] / repr(C)] wrapper around sys::JNINativeMethod
        //  - NativeMethod only has an `unsafe` constructor that requires the caller to ensure that
        //    the function pointer is valid and matches the signature
        let res = unsafe {
            jni_call_with_catch!(
                catch |env| {
                    e: crate::exceptions::JNoSuchMethodError => {
                        let msg = e.as_throwable().get_message(env).ok();
                        let msg = if let Some(msg) = msg { msg.to_string() } else { String::new() };
                        Err(Error::NoSuchMethod(msg))
                    },
                    else => Err(Error::JniCall(JniError::Unknown)),
                },
                self,
                v1_1,
                RegisterNatives,
                class.as_ref().as_raw(),
                methods.as_ptr() as *mut sys::JNINativeMethod,
                methods.len() as jint
            )?
        };

        // Ensure that `class` isn't dropped before the JNI call returns.
        drop(class);

        jni_error_code_to_result(res)
    }

    /// Unbind all native methods of class.
    pub fn unregister_native_methods<'other_local, T>(&mut self, class: T) -> Result<()>
    where
        T: Desc<'local, JClass<'other_local>>,
    {
        let class = class.lookup(self)?;
        let res = unsafe {
            jni_call_post_check_ex!(self, v1_1, UnregisterNatives, class.as_ref().as_raw())?
        };

        // Ensure that `class` isn't dropped before the JNI call returns.
        drop(class);

        jni_error_code_to_result(res)
    }

    /// Returns an [`AutoElements`] to access the elements of the given Java `array`.
    ///
    /// # Safety
    ///
    /// See: [JPrimitiveArray::get_elements] for more details
    #[deprecated(
        since = "0.22.0",
        note = "use JPrimitiveArray::get_elements instead. This API will be removed in a future version"
    )]
    pub unsafe fn get_array_elements<'array_local, T, TArrayRef>(
        &self,
        array: TArrayRef,
        mode: ReleaseMode,
    ) -> Result<AutoElements<'array_local, T, TArrayRef>>
    where
        T: TypeArray,
        TArrayRef: AsRef<JPrimitiveArray<'array_local, T>> + Reference,
    {
        AutoElements::new(self, array, mode)
    }

    /// Returns an [`AutoElementsCritical`] to access the elements of the given Java `array`.
    ///
    /// # Safety
    ///
    /// See: [JPrimitiveArray::get_elements_critical] for more details
    #[deprecated(
        since = "0.22.0",
        note = "use JPrimitiveArray::get_elements_critical instead. This API will be removed in a future version"
    )]
    pub unsafe fn get_array_elements_critical<'array_local, T, TArrayRef>(
        &self,
        array: TArrayRef,
        mode: ReleaseMode,
    ) -> Result<AutoElementsCritical<'array_local, T, TArrayRef>>
    where
        T: TypeArray,
        TArrayRef: AsRef<JPrimitiveArray<'array_local, T>> + Reference,
    {
        AutoElementsCritical::new(self, array, mode)
    }
}

/// The outcome of an operation that may succeed, fail with an error, or panic.
///
/// This enum is used to encapsulate the result of operations within native methods
/// where extra care is needed to handle errors and panics gracefully before
/// returning a value to the Java environment.
#[derive(Debug)]
pub enum Outcome<T, E> {
    /// Contains the success value
    Ok(T),
    /// Contains the error value
    Err(E),
    /// Contains the panic value
    Panic(Box<dyn std::any::Any + Send + 'static>),
}

/// An opaque wrapper around an [`Outcome<T, Error>`] that supports mapping
/// errors within native methods (via [`ErrorPolicy`]), with access to an
/// [`Env`] reference.
///
/// This is returned by [`EnvUnowned::with_env`] and is designed for use within
/// native method implementations where unwinding can't be caught by the JVM and
/// will abort the process.
///
/// Once you have an [`EnvOutcome`] you must resolve it to a value that can be
/// returned to the Java environment.
///
/// An [`EnvOutcome`] is resolved into a return value by calling
/// [`EnvOutcome::resolve`] or [`EnvOutcome::resolve_with`] with the help of an
/// [`ErrorPolicy`] that can customize how errors and panics are handled before
/// returning a value.
///
/// There are several built-in error policies in the `jni::errors` module, and
/// you can also implement your own by implementing the [`ErrorPolicy`] trait.
/// See:
///
/// - [`ThrowRuntimeExAndDefault`]: an `ErrorPolicy` that throws any error as a
///   `java.lang.RuntimeException` and returns a default value.
/// - [`LogErrorAndDefault`]: an `ErrorPolicy` that logs errors and returns a
///   default value.
/// - [`LogContextErrorAndDefault`]: an `ErrorPolicy` that logs errors, with a
///   given context string, and returns a default value.
///
/// # Examples
///
/// ## Map Rust errors and panics to Java exceptions:
/// ```rust,no_run
/// # use jni::objects::{JObject, JString};
/// # use jni::errors::ThrowRuntimeExAndDefault;
/// #[unsafe(no_mangle)]
/// pub extern "system" fn Java_com_example_MyClass_myNativeMethod<'caller>(
///     mut unowned_env: jni::EnvUnowned<'caller>,
///     _this: JObject<'caller>,
///     arg: JString<'caller>,
/// ) -> JObject<'caller> {
///     unowned_env.with_env(|env| -> jni::errors::Result<_> {
///         // Use `env` to call Java methods or access fields.
///         Ok(JObject::null())
///     }).resolve::<ThrowRuntimeExAndDefault>()
/// }
/// ```
///
/// ## Log errors with a context string and return a default value:
/// ```rust,no_run
/// # use jni::objects::{JObject, JString};
/// # use jni::errors::LogContextErrorAndDefault;
/// #[unsafe(no_mangle)]
/// pub extern "system" fn Java_com_example_MyClass_myNativeMethod<'caller>(
///    mut unowned_env: jni::EnvUnowned<'caller>,
///    _this: JObject<'caller>,
///    arg: JString<'caller>,
/// ) -> JObject<'caller> {
///    unowned_env.with_env(|env| -> jni::errors::Result<_> {
///       // Use `env` to call Java methods or access fields.
///       Ok(JObject::null())
///   }).resolve_with::<LogContextErrorAndDefault, _>(|| {
///     format!("in myNativeMethod with arg: {arg}")
///   })
/// }
/// ```
#[must_use = "The outcome must be resolved to a value that can be returned to Java. See ::resolve or ::resolve_with"]
#[derive(Debug)]
pub struct EnvOutcome<'local, T, E> {
    raw_env: *mut crate::sys::JNIEnv,
    outcome: Outcome<T, E>,
    _invariant: std::marker::PhantomData<&'local mut ()>, // !Send/!Sync + tie to frame
}

impl<'local, T, E> EnvOutcome<'local, T, E> {
    pub(crate) fn new(raw_env: *mut crate::sys::JNIEnv, outcome: Outcome<T, E>) -> Self {
        Self {
            raw_env,
            outcome,
            _invariant: Default::default(),
        }
    }

    /// No captures (fast path).
    pub fn resolve<'native_method, P>(self) -> T
    where
        P: ErrorPolicy<T, E, Captures<'local, 'native_method> = ()>,
        T: Default + 'native_method,
        'local: 'native_method,
    {
        self.resolve_with::<P, _>(|| ())
    }

    /// Builder can borrow locals (via 'm) and use the temporary Env<'cf>.
    pub fn resolve_with<'native_method, P, F>(self, capture: F) -> T
    where
        P: ErrorPolicy<T, E>,
        T: Default + 'native_method,
        F: FnOnce() -> <P as ErrorPolicy<T, E>>::Captures<'local, 'native_method>,
        'local: 'native_method,
    {
        // Rebuild Env<'cf> (AttachGuard hidden), then build captures and map once.
        // All calls are guarded with catch_unwind; fall back to last_resort on failure.
        self.resolve_inner::<P, F>(capture)
    }

    fn resolve_inner<'native_method, P, F>(self, capture: F) -> T
    where
        P: ErrorPolicy<T, E>,
        T: Default + 'native_method,
        F: FnOnce() -> <P as ErrorPolicy<T, E>>::Captures<'local, 'native_method>,
        'local: 'native_method,
    {
        unsafe {
            let mut guard: AttachGuard<'local> = AttachGuard::from_unowned(self.raw_env);
            let env = guard.borrow_env_mut();

            match self.outcome {
                Outcome::Ok(t) => t,
                Outcome::Err(e) => {
                    let mut cap = capture();
                    std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
                        match P::on_error(env, &mut cap, e) {
                            Ok(t) => t,
                            Err(err) => P::on_internal_jni_error(&mut cap, err),
                        }
                    }))
                    .unwrap_or_else(|payload| P::on_internal_panic(&mut cap, payload))
                }
                Outcome::Panic(p) => {
                    let mut cap = capture();
                    std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
                        match P::on_panic(env, &mut cap, p) {
                            Ok(t) => t,
                            Err(err) => P::on_internal_jni_error(&mut cap, err),
                        }
                    }))
                    .unwrap_or_else(|payload| P::on_internal_panic(&mut cap, payload))
                }
            }
        }
    }

    /// Consumes the `EnvOutcome`, returning the underlying `Outcome<T, E>`.
    pub fn into_outcome(self) -> Outcome<T, E> {
        self.outcome
    }
}

/// Represents an external (unowned) JNI stack frame and thread attachment that
/// was passed to a native method call.
///
/// This is an FFI safe wrapper around a [`crate::sys::JNIEnv`] pointer that has
/// been passed as the first argument to a native method call, and represents
/// an implicit JNI thread attachment.
///
/// For example, you can use it with a native method implementation like this:
/// ```rust,no_run
/// # use jni::objects::{JObject, JString};
/// # use jni::errors::ThrowRuntimeExAndDefault;
/// #[unsafe(no_mangle)]
/// pub extern "system" fn Java_com_example_MyClass_myNativeMethod<'caller>(
///     mut unowned_env: jni::EnvUnowned<'caller>,
///     _this: JObject<'caller>,
///     arg: JString<'caller>,
/// ) -> JObject<'caller> {
///     unowned_env.with_env(|env| -> jni::errors::Result<_> {
///         // Use `env` to call Java methods or access fields.
///         Ok(JObject::null())
///     }).resolve::<ThrowRuntimeExAndDefault>()
/// }
/// ```
#[repr(transparent)]
#[derive(Debug)]
pub struct EnvUnowned<'local> {
    ptr: *mut jni_sys::JNIEnv,
    _lifetime: std::marker::PhantomData<&'local ()>,
}

impl<'local> EnvUnowned<'local> {
    /// Runs a closure with a [`Env`] based on an unowned JNI thread attachment
    /// associated with an external JNI stack frame.
    ///
    /// This API is specifically intended to be used within native/foreign Java
    /// method implementations in cases where you have named the lifetime for
    /// the caller's JNI stack frame.
    ///
    /// It returns an [`EnvOutcome`] that supports mapping errors with access to
    /// an [`Env`], so you may choose to throw errors as exceptions.
    ///
    /// To avoid the risk of unwinding into the JVM (which will abort the
    /// process) this API wraps the closure in a [`catch_unwind`] to catch any
    /// panics. Any panic can be handled via the [`ErrorPolicy`] given to
    /// [`EnvOutcome::resolve`] or handled directly via [`EnvOutcome::into_outcome`].
    ///
    /// Note: This API does not create a new JNI stack frame, since the JVM will
    /// clean up the JNI stack frame when the native method returns.
    ///
    /// Note: This API returns an [`EnvOutcome`]
    pub fn with_env<F, T, E>(&mut self, f: F) -> EnvOutcome<'local, T, E>
    where
        F: FnOnce(&mut Env<'local>) -> std::result::Result<T, E>,
        E: From<Error>,
    {
        // Safety: we trust that self.ptr a valid, non-null pointer
        let mut guard: AttachGuard<'local> = unsafe { AttachGuard::from_unowned(self.ptr) };
        let env = guard.borrow_env_mut();
        let result = catch_unwind(AssertUnwindSafe(|| f(env)));
        let outcome = match result {
            Ok(ret) => match ret {
                Ok(t) => Outcome::Ok(t),
                Err(e) => Outcome::Err(e),
            },
            Err(payload) => Outcome::Panic(payload),
        };
        EnvOutcome::new(self.ptr, outcome)
    }

    /// Runs a closure with a [`Env`] based on an unowned JNI thread attachment
    /// associated with an external JNI stack frame.
    ///
    /// This API is specifically intended to be used within native/foreign Java
    /// method implementations in cases where you have named the lifetime for
    /// the caller's JNI stack frame.
    ///
    /// Since it would lead to undefined behaviour to allow Rust code to unwind
    /// across a native method call boundary, you probably want to use
    /// [`EnvUnowned::with_env`] instead, which will wrap the closure
    /// in a `catch_unwind` to catch any panics.
    ///
    /// Note: This API does not create a new JNI stack frame, which is normally
    /// what you want when implementing a native method, since the JVM will
    /// clean up the JNI stack frame when the native method returns.
    pub fn with_env_no_catch<F, T, E>(&mut self, f: F) -> EnvOutcome<'local, T, E>
    where
        F: FnOnce(&mut Env<'local>) -> std::result::Result<T, E>,
        E: From<Error>,
    {
        // Safety: we trust that self.ptr a valid, non-null pointer
        let mut guard: AttachGuard<'local> = unsafe { AttachGuard::from_unowned(self.ptr) };
        let result = f(guard.borrow_env_mut());
        match result {
            Ok(t) => EnvOutcome::new(self.ptr, Outcome::Ok(t)),
            Err(e) => EnvOutcome::new(self.ptr, Outcome::Err(e)),
        }
    }

    /// Creates a new `EnvUnowned` from a raw [`crate::sys::JNIEnv`] pointer.
    ///
    /// It should be very uncommon to use this method directly, but could be
    /// useful if you are given a raw [`crate::sys::JNIEnv`] pointer that you
    /// know represents a valid JNI attachment for the current thread.
    ///
    /// If you are implementing a native method in Rust though, you should
    /// prefer to use the [`EnvUnowned`] type as the first argument to your
    /// native method and avoid the need to use a raw pointer.
    ///
    /// If you have a raw [`crate::sys::JNIEnv`] pointer, this API should be
    /// marginally safer than using [`crate::AttachGuard`] manually
    /// since the attach guard management will be hidden within the
    /// [`Self::with_env`] and [`Self::with_env_no_catch`] methods.
    ///
    /// Beware that [`Self::with_env`] and [`Self::with_env_no_catch`] will not
    /// create a new JNI stack frame, so if you are not implementing a native
    /// method with a JNI stack frame that will be cleaned up on return, you may
    /// need to consider the risk of leaking local references into the current
    /// stack frame (JNI references are only cleaned up when the stack frame is
    /// popped)
    ///
    /// # Safety
    ///
    /// The pointer must be a valid, non-null pointer to a `jni_sys::JNIEnv`
    /// that represents an attachment of the current thread to a Java VM.
    ///
    /// The assigned lifetime must not outlive the JNI stack frame that owns the
    /// `Env` pointer. For example it would _never_ be safe to use `'static`.
    pub unsafe fn from_raw(ptr: *mut jni_sys::JNIEnv) -> Self {
        assert!(!ptr.is_null(), "EnvUnowned pointer must not be null");
        Self {
            ptr,
            _lifetime: std::marker::PhantomData,
        }
    }

    /// Returns the raw pointer to the underlying [`crate::sys::JNIEnv`].
    pub fn as_raw(&self) -> *mut jni_sys::JNIEnv {
        self.ptr
    }

    /// Consumes the [`EnvUnowned`] and returns the raw pointer to the underlying [`crate::sys::JNIEnv`].
    pub fn into_raw(self) -> *mut jni_sys::JNIEnv {
        self.ptr
    }
}

#[repr(transparent)]
#[derive(Debug, Clone, Copy)]
/// Native method descriptor for use with [`Env::register_native_methods`].
///
/// This is a `#[repr(transparent)]` / `repr(C)` wrapper around the [`crate::sys::JNINativeMethod`]
/// struct but with the additional constraint that it can only be constructed via an `unsafe`
/// [`Self::from_raw_parts`] method that requires the caller to ensure that the function pointer is
/// valid and matches the signature.
pub struct NativeMethod<'desc> {
    desc: JNINativeMethod,
    _phantom: PhantomData<&'desc JNIStr>,
}

impl<'desc> NativeMethod<'desc> {
    /// Creates a new `NativeMethod` descriptor.
    ///
    /// # Safety
    ///
    /// The `fn_ptr` must be a valid pointer to a function that matches the
    /// signature specified by `sig`.
    ///
    /// For example, with the signature `"(I)Ljava/lang/String;"`...
    ///
    /// A **static method** must point to a function with the signature:
    ///
    /// `fn<'local>(unowned_env: EnvUnowned<'local>, class: JClass<'local>, arg0: jint) -> JString<'local>`.
    ///
    /// An **instance method** must point to a function with the signature:
    ///
    /// `fn<'local>(unowned_env: EnvUnowned<'local>, this: JObject<'local>, arg0: jint) -> JString<'local>`.
    ///
    /// or some specific `this` type like:
    ///
    /// `fn<'local>(unowned_env: EnvUnowned<'local>, this: MyType<'local>, arg0: jint) -> JString<'local>`.
    pub const unsafe fn from_raw_parts(
        name: &'desc JNIStr,
        sig: &'desc JNIStr,
        fn_ptr: *mut c_void,
    ) -> NativeMethod<'desc> {
        NativeMethod {
            desc: JNINativeMethod {
                name: name.as_ptr() as *mut c_char,
                signature: sig.as_ptr() as *mut c_char,
                fnPtr: fn_ptr as *mut c_void,
            },
            _phantom: PhantomData,
        }
    }
}

/// Guard for a lock on a java object. This gets returned from the `lock_obj`
/// method.
#[derive(Debug)]
#[must_use]
pub struct MonitorGuard<'local> {
    obj: sys::jobject,
    life: PhantomData<&'local ()>,
}

impl Drop for MonitorGuard<'_> {
    fn drop(&mut self) {
        // Panics:
        //
        // The first `.expect()` is OK because the `&self` reference is enough to prove that
        // `JavaVM::singleton` must have been initialized and won't panic. (A MonitorGuard can only
        // be created with a Env reference)
        //
        // The second `.expect()` is OK because the guard is associated with a Env lifetime, so
        // it logically shouldn't be possible for the thread to become detached before the monitor
        // is dropped.
        JavaVM::singleton()
            .expect("JavaVM singleton must be initialized")
            .with_top_local_frame(|env| -> crate::errors::Result<()> {
                // Safety:
                //
                // This relies on `MonitorGuard` not being `Send` to maintain the
                // invariant that "The current thread must be the owner of the monitor
                // associated with the underlying Java object referred to by obj"
                //
                // This also means we can assume the `IllegalMonitorStateException`
                // exception can't be thrown due to the current thread not owning
                // the monitor.
                let res =
                    unsafe { ex_safe_jni_call_no_post_check_ex!(env, v1_1, MonitorExit, self.obj) };
                if let Err(err) = jni_error_code_to_result(res) {
                    log::error!("error releasing java monitor: {err}");
                }

                Ok(())
            })
            .expect("MonitorGuard dropped on detached thread");
    }
}

#[cfg(test)]
static_assertions::assert_not_impl_any!(MonitorGuard: Send);