or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

c-interop.mdcollections.mdconfig.mdindex.mdjni-utils.mdnative-bridge.mdnative-image.mdpolyglot.mdsubstitutions.mdword.md

jni-utils.mddocs/

0

# JNI Utils

1

2

Simplified and safer JNI programming utilities providing type-safe wrappers, automatic exception handling, and streamlined native method integration.

3

4

## Capabilities

5

6

### JNI Helper Functions

7

8

Core utility class providing simplified JNI operations with automatic error handling and type safety.

9

10

```java { .api }

11

/**

12

* Main JNI utility class with helper methods for common operations

13

*/

14

public final class JNI {

15

/** Create new local reference to object */

16

public static <T> T NewLocalRef(T obj);

17

18

/** Delete local reference */

19

public static void DeleteLocalRef(Object obj);

20

21

/** Create new global reference */

22

public static <T> T NewGlobalRef(T obj);

23

24

/** Delete global reference */

25

public static void DeleteGlobalRef(Object obj);

26

27

/** Create new weak global reference */

28

public static <T> T NewWeakGlobalRef(T obj);

29

30

/** Delete weak global reference */

31

public static void DeleteWeakGlobalRef(Object obj);

32

33

/** Get Java object class */

34

public static Class<?> GetObjectClass(Object obj);

35

36

/** Create new object array */

37

public static Object[] NewObjectArray(int length, Class<?> elementClass, Object initialElement);

38

39

/** Get object array element */

40

public static Object GetObjectArrayElement(Object[] array, int index);

41

42

/** Set object array element */

43

public static void SetObjectArrayElement(Object[] array, int index, Object value);

44

45

/** Throw new Java exception */

46

public static void ThrowNew(Class<? extends Throwable> exceptionClass, String message);

47

48

/** Check for pending exception */

49

public static boolean ExceptionCheck();

50

51

/** Clear pending exception */

52

public static void ExceptionClear();

53

}

54

```

55

56

**Usage Examples:**

57

58

```java

59

import org.graalvm.jniutils.*;

60

61

public class JNIExample {

62

public void manageReferences(Object javaObject) {

63

// Create global reference for long-term storage

64

Object globalRef = JNI.NewGlobalRef(javaObject);

65

66

try {

67

// Use global reference in native operations

68

processObject(globalRef);

69

} finally {

70

// Always clean up global references

71

JNI.DeleteGlobalRef(globalRef);

72

}

73

}

74

75

public void handleExceptions() {

76

try {

77

riskyOperation();

78

} catch (Exception e) {

79

// Convert to JNI exception

80

JNI.ThrowNew(RuntimeException.class, e.getMessage());

81

}

82

}

83

}

84

```

85

86

### JNI Utilities

87

88

Extended utility functions for advanced JNI operations and native integration.

89

90

```java { .api }

91

/**

92

* Additional JNI convenience methods for advanced operations

93

*/

94

public final class JNIUtil {

95

/** Get field ID for named field */

96

public static long GetFieldID(Class<?> clazz, String name, String signature);

97

98

/** Get method ID for named method */

99

public static long GetMethodID(Class<?> clazz, String name, String signature);

100

101

/** Get static field ID */

102

public static long GetStaticFieldID(Class<?> clazz, String name, String signature);

103

104

/** Get static method ID */

105

public static long GetStaticMethodID(Class<?> clazz, String name, String signature);

106

107

/** Call object method with arguments */

108

public static Object CallObjectMethod(Object obj, long methodID, Object... args);

109

110

/** Call static object method */

111

public static Object CallStaticObjectMethod(Class<?> clazz, long methodID, Object... args);

112

113

/** Get object field value */

114

public static Object GetObjectField(Object obj, long fieldID);

115

116

/** Set object field value */

117

public static void SetObjectField(Object obj, long fieldID, Object value);

118

119

/** Get static object field value */

120

public static Object GetStaticObjectField(Class<?> clazz, long fieldID);

121

122

/** Set static object field value */

123

public static void SetStaticObjectField(Class<?> clazz, long fieldID, Object value);

124

125

/** Convert Java string to C string */

126

public static CCharPointer GetStringUTFChars(String str);

127

128

/** Release C string created from Java string */

129

public static void ReleaseStringUTFChars(String str, CCharPointer chars);

130

}

131

```

132

133

### Method Scope Management

134

135

Scoped execution wrapper for JNI methods ensuring proper cleanup and exception handling.

136

137

```java { .api }

138

/**

139

* Scoped JNI method execution with automatic resource management

140

*/

141

public final class JNIMethodScope implements AutoCloseable {

142

/** Create new method scope for JNI operations */

143

public static JNIMethodScope scope();

144

145

/** Execute operation within this scope */

146

public <T> T scope(Supplier<T> operation);

147

148

/** Execute void operation within this scope */

149

public void scope(Runnable operation);

150

151

/** Close scope and clean up resources */

152

public void close();

153

154

/** Get JNI environment for this scope */

155

public JNIEnvironment getEnvironment();

156

}

157

```

158

159

**Usage Examples:**

160

161

```java

162

public class ScopedJNIExample {

163

public String processWithScope(Object javaObject) {

164

try (JNIMethodScope scope = JNIMethodScope.scope()) {

165

return scope.scope(() -> {

166

// All JNI operations automatically cleaned up

167

Class<?> clazz = JNI.GetObjectClass(javaObject);

168

long methodID = JNIUtil.GetMethodID(clazz, "toString", "()Ljava/lang/String;");

169

return (String) JNIUtil.CallObjectMethod(javaObject, methodID);

170

});

171

}

172

}

173

}

174

```

175

176

### Exception Handling

177

178

Automatic exception translation between Java and JNI with proper cleanup.

179

180

```java { .api }

181

/**

182

* Automatic exception translation and handling for JNI operations

183

*/

184

public final class JNIExceptionWrapper {

185

/** Wrap JNI operation with exception handling */

186

public static <T> T wrapException(Supplier<T> operation);

187

188

/** Wrap void JNI operation with exception handling */

189

public static void wrapException(Runnable operation);

190

191

/** Convert native exception to Java exception */

192

public static RuntimeException convertException(Throwable nativeException);

193

194

/** Handle pending JNI exception */

195

public static void handlePendingException();

196

}

197

198

/**

199

* Entry point generation for JNI exception wrappers

200

*/

201

public final class JNIExceptionWrapperEntryPoints {

202

/** Generate entry point with exception wrapping */

203

public static void generateEntryPoint(String methodName, Class<?>[] parameterTypes);

204

205

/** Register exception wrapper for method */

206

public static void registerWrapper(String methodName, Object wrapper);

207

}

208

```

209

210

### HotSpot Object Support

211

212

Utilities for working with HotSpot VM objects in native image contexts.

213

214

```java { .api }

215

/**

216

* HotSpot object handling utilities for native image integration

217

*/

218

public final class HSObject {

219

/** Convert HotSpot object to native representation */

220

public static Object toNative(Object hotSpotObject);

221

222

/** Convert native object to HotSpot representation */

223

public static Object fromNative(Object nativeObject);

224

225

/** Check if object is HotSpot object */

226

public static boolean isHotSpotObject(Object obj);

227

228

/** Get HotSpot object class */

229

public static Class<?> getHotSpotClass(Object obj);

230

231

/** Invoke HotSpot method on object */

232

public static Object invokeHotSpotMethod(Object obj, String methodName, Object... args);

233

}

234

```

235

236

### JNI Entry Points

237

238

Annotation-based JNI entry point generation for simplified native method binding.

239

240

```java { .api }

241

/**

242

* Annotation for generating JNI entry points

243

*/

244

@Target(ElementType.METHOD)

245

@Retention(RetentionPolicy.RUNTIME)

246

public @interface JNIEntryPoint {

247

/** JNI method name (defaults to Java method name) */

248

String name() default "";

249

250

/** JNI signature (auto-generated if not specified) */

251

String signature() default "";

252

253

/** Whether to include exception handling */

254

boolean exceptionHandling() default true;

255

256

/** Whether to use method scope */

257

boolean useScope() default true;

258

}

259

```

260

261

**Usage Examples:**

262

263

```java

264

public class NativeMethodExample {

265

@JNIEntryPoint(name = "processData")

266

public static String processData(byte[] data, int offset, int length) {

267

// Implementation automatically wrapped with exception handling

268

return new String(data, offset, length);

269

}

270

271

@JNIEntryPoint(exceptionHandling = false, useScope = false)

272

public static int fastComputation(int a, int b) {

273

// High-performance method without overhead

274

return a * b + a / b;

275

}

276

}

277

```

278

279

### Native Bridge Support

280

281

Integration support for native bridge communication between different runtime environments.

282

283

```java { .api }

284

/**

285

* Native bridge integration support for JNI utilities

286

*/

287

public final class NativeBridgeSupport {

288

/** Initialize native bridge for JNI operations */

289

public static void initializeBridge();

290

291

/** Create bridge-compatible JNI environment */

292

public static JNIEnvironment createBridgeEnvironment();

293

294

/** Convert bridge object to JNI object */

295

public static Object bridgeToJNI(Object bridgeObject);

296

297

/** Convert JNI object to bridge object */

298

public static Object jniToBridge(Object jniObject);

299

300

/** Check if native bridge is available */

301

public static boolean isBridgeAvailable();

302

}

303

```

304

305

## Types

306

307

```java { .api }

308

/**

309

* JNI environment interface for low-level operations

310

*/

311

public interface JNIEnvironment {

312

/** Get JNI version */

313

int getVersion();

314

315

/** Find Java class by name */

316

Class<?> findClass(String name);

317

318

/** Register native methods */

319

void registerNatives(Class<?> clazz, JNINativeMethod[] methods);

320

321

/** Unregister native methods */

322

void unregisterNatives(Class<?> clazz);

323

}

324

325

/**

326

* JNI native method descriptor

327

*/

328

public static class JNINativeMethod {

329

/** Method name */

330

public final String name;

331

332

/** Method signature */

333

public final String signature;

334

335

/** Function pointer */

336

public final CFunctionPointer fnPtr;

337

338

public JNINativeMethod(String name, String signature, CFunctionPointer fnPtr);

339

}

340

341

/**

342

* Functional interface for supplying values

343

*/

344

public interface Supplier<T> {

345

T get();

346

}

347

```