Documentation ¶
Overview ¶
JNIGI (Java Native Interface Go Interface)
A package to access Java from Go code.
All constructor and method call functions convert parameter arguments and return values.
Arguments are converted from Go to Java if:
- The type is Go built in type and there is an equivalent Java "primitive" type.
- The type is a slice of such a Go built in type.
- The type implements the ToJavaConverter interface
Return values are converted from Java to Go if:
- The type is a Java "primitive" type.
- The type is a Java array of a "primitive" type.
- The type implements the ToGoConverter interface
Go Builtin to/from Java "primitive":
bool boolean byte byte int16 short uint16 char int int (also int32 -> int) int64 long float32 float float64 double
Index ¶
- Constants
- func AttemptToFindJVMLibPath() string
- func CreateJVM(jvmInitArgs *JVMInitArgs) (*JVM, *Env, error)
- func LoadJVMLib(jvmLibPath string) error
- func UseJVM(pvm unsafe.Pointer, penv unsafe.Pointer, thiz unsafe.Pointer) (*JVM, *Env)
- type ArrayRef
- type ByteArray
- type ClassInfoGetter
- type ClassLoaderRef
- type Env
- func (j *Env) CallStaticMethod(className string, methodName string, dest interface{}, args ...interface{}) error
- func (j *Env) DeleteGlobalRef(o *ObjectRef)
- func (j *Env) DeleteGlobalRefCache()
- func (j *Env) DeleteLocalRef(o *ObjectRef)
- func (j *Env) EnsureLocalCapacity(capacity int32) error
- func (j *Env) FindClass(className string) (*ObjectRef, error)
- func (j *Env) FromObjectArray(objRef *ObjectRef) []*ObjectRef
- func (r *Env) GetClassLoader(obj *ObjectRef) *ClassLoaderRef
- func (j *Env) GetJVM() (*JVM, error)
- func (j *Env) GetStaticField(className string, fieldName string, dest interface{}) error
- func (j *Env) GetUTF8String() *ObjectRef
- func (j *Env) NewByteArray(n int) *ByteArray
- func (j *Env) NewByteArrayFromObject(o *ObjectRef) *ByteArray
- func (j *Env) NewByteArrayFromSlice(src []byte) *ByteArray
- func (j *Env) NewGlobalRef(o *ObjectRef) *ObjectRef
- func (j *Env) NewObject(className string, args ...interface{}) (*ObjectRef, error)
- func (j *Env) PopLocalFrame(result *ObjectRef) *ObjectRef
- func (j *Env) PrecalculateSignature(sig string)
- func (j *Env) PushLocalFrame(capacity int32) error
- func (j *Env) RegisterNative(className, methodName string, returnType TypeSpec, params []interface{}, ...) error
- func (r *Env) SetClassLoader(classLoader *ClassLoaderRef)
- func (j *Env) SetStaticField(className string, fieldName string, value interface{}) error
- func (j *Env) ToGoArray(array jobject, aType Type) (interface{}, error)
- func (j *Env) ToJavaArray(src interface{}) (jobject, error)
- func (j *Env) ToObjectArray(objRefs []*ObjectRef, className string) (arrayRef *ObjectRef)
- type ExceptionHandler
- type ExceptionHandlerFunc
- type JVM
- type JVMInitArgs
- type ObjectArrayType
- type ObjectRef
- func (o *ObjectRef) CallMethod(env *Env, methodName string, dest interface{}, args ...interface{}) error
- func (o *ObjectRef) CallNonvirtualMethod(env *Env, className string, methodName string, dest interface{}, ...) error
- func (o *ObjectRef) Cast(className string) *ObjectRef
- func (o *ObjectRef) GetClassName() string
- func (o *ObjectRef) GetField(env *Env, fieldName string, dest interface{}) error
- func (o *ObjectRef) IsArray() bool
- func (o *ObjectRef) IsInstanceOf(env *Env, className string) (bool, error)
- func (o *ObjectRef) IsNil() bool
- func (o *ObjectRef) JObject() jobject
- func (o *ObjectRef) SetField(env *Env, fieldName string, value interface{}) error
- type ObjectType
- type StackTraceElement
- type ThrowableError
- type ToGoConverter
- type ToJavaConverter
- type Type
- type TypeGetter
- type TypeSpec
Constants ¶
const ( JNI_VERSION_1_2 = C.JNI_VERSION_1_2 JNI_VERSION_1_4 = C.JNI_VERSION_1_4 JNI_VERSION_1_6 = C.JNI_VERSION_1_6 JNI_VERSION_1_8 = C.JNI_VERSION_1_8 JNI_VERSION_9 = C.JNI_VERSION_9 JNI_VERSION_10 = C.JNI_VERSION_10 DEFAULT_VERSION = JNI_VERSION_1_6 )
const ( Void = Type(1 << iota) Boolean Byte Char Short Int Long Float Double Object Array )
Variables ¶
This section is empty.
Functions ¶
func AttemptToFindJVMLibPath ¶
func AttemptToFindJVMLibPath() string
AttemptToFindJVMLibPath tries to find the full path to the JVM shared library file
func CreateJVM ¶
func CreateJVM(jvmInitArgs *JVMInitArgs) (*JVM, *Env, error)
CreateJVM calls JNI CreateJavaVM and returns references to the JVM and the initial environment. Use NewJVMInitArgs to create jvmInitArgs.
Must call runtime.LockOSThread() first.
func LoadJVMLib ¶
LoadJVMLib loads libjvm.so as specified in jvmLibPath
func UseJVM ¶
UseJVM initialized jnigi with an existing JVM.
This is important for Android, where the existing JVM must be used when running inside an Android app--i.e. Go code built as a shared library.
An existing JVM may be obtained through a JNI call made by the JVM after System.loadLibrary:
JNIEXPORT void JNICALL Java_foo_bar_Baz_00024_funcName(JNIEnv *env, jobject thiz) { // Pass env, thiz and the result of (*env)->GetJavaVM() into Go, then UseJVM() }
If 'thiz' is specified, its class loader will be used to find non-system classes. This should pick up custom classes, as well as libraries from dependencies { } in build.gradle.
Parameters can also be derived from the JNI_OnLoad() call made during System.loadLibrary(). In this case, 'thiz' should be a custom class in order to retrieve a useful class loader.
Types ¶
type ArrayRef ¶
ArrayRef just disables auto conversion of Java arrays to Go slices
func NewArrayRef ¶
func (*ArrayRef) ConvertToGo ¶
Just hold on to the reference to the array jobject
type ByteArray ¶
type ByteArray struct {
// contains filtered or unexported fields
}
ByteArray holds a JNI JbyteArray
func (*ByteArray) CopyBytes ¶
CopyBytes creates a go slice of bytes of same length as byte array, calls GetCritical, copies byte array into go slice, calls ReleaseCritical, returns go slice.
func (*ByteArray) GetCritical ¶
GetCritical calls JNI GetPrimitiveArrayCritical
func (*ByteArray) ReleaseCritical ¶
GetCritical calls JNI ReleasePrimitiveArrayCritical
type ClassInfoGetter ¶
ClassInfoGetter is implemented by *ObjectRef, *CastedObjectRef to get type info for object values.
type ClassLoaderRef ¶
type ClassLoaderRef struct {
// contains filtered or unexported fields
}
A reference to a class loader object
type Env ¶
type Env struct { ExceptionHandler ExceptionHandler // contains filtered or unexported fields }
Env holds a JNIEnv value. Methods in this package often require an *Env pointer to specify the JNI Env to run in, so it might be good to store the Env as a package variable.
func (*Env) CallStaticMethod ¶
func (j *Env) CallStaticMethod(className string, methodName string, dest interface{}, args ...interface{}) error
CallStaticMethod calls static method methodName in class className with arguments args and stores return value in dest.
func (*Env) DeleteGlobalRef ¶
DeleteGlobalRef deletes global object reference o.
func (*Env) DeleteGlobalRefCache ¶
func (j *Env) DeleteGlobalRefCache()
DeleteGlobalRefCache deletes all globalRef that are in classCache. This methods should be called when an instance of *Env gets out of scope
func (*Env) DeleteLocalRef ¶
DeleteLocalRef deletes object reference o in Env j.
func (*Env) EnsureLocalCapacity ¶
EnsureLocalCapacity calls JNI EnsureLocalCapacity on Env j
func (*Env) FindClass ¶
FindCLass returns reference to java/lang/Class Argument is className of target class
func (*Env) FromObjectArray ¶
FromObjectArray converts an Java array of objects objRef in to a slice of *ObjectRef which is returned.
func (*Env) GetClassLoader ¶
func (r *Env) GetClassLoader(obj *ObjectRef) *ClassLoaderRef
Get a class loader object from an existing object obj
func (*Env) GetStaticField ¶
GetField gets field fieldName in class className, stores value in dest.
func (*Env) GetUTF8String ¶
GetUTF8String return global reference to java/lang/String containing "UTF-8"
func (*Env) NewByteArray ¶
NewByteArray calls JNI NewByteArray
func (*Env) NewByteArrayFromObject ¶
NewByteArrayFromObject creates new ByteArray and sets it from ObjectRef o.
func (*Env) NewByteArrayFromSlice ¶
NewByteArrayFromSlice calls JNI NewByteArray and GetCritical, copies src to byte array, calls JNI Release Critical. Returns new byte array.
func (*Env) NewGlobalRef ¶
NewGlobalRef creates a new object reference to o in Env j.
func (*Env) NewObject ¶
NewObject calls JNI NewObjectA, className class name of new object, args arguments to constructor.
func (*Env) PopLocalFrame ¶
PopLocalFrame calls JNI popLocalFrame on Env j
func (*Env) PrecalculateSignature ¶
PrecalculateSignature sets the signature of the next call to sig, disables automatic signature building.
func (*Env) PushLocalFrame ¶
PushLocalFrame calls JNI PushLocalFrame on Env j
func (*Env) RegisterNative ¶
func (j *Env) RegisterNative(className, methodName string, returnType TypeSpec, params []interface{}, fptr interface{}) error
RegisterNative calls JNI RegisterNative for class className, method methodName with return type returnType and parameters params, fptr is used as native function.
func (*Env) SetClassLoader ¶
func (r *Env) SetClassLoader(classLoader *ClassLoaderRef)
Set the env to look up classes using classloader, (it still fall back to JNI findClass function)
func (*Env) SetStaticField ¶
SetField sets field fieldName in class className to value.
func (*Env) ToGoArray ¶
ToGoArray converts Java prim array object in array with type aType to returned go array. Normally this method does not need to be called because New/Call/Field methods all call this internally.
func (*Env) ToJavaArray ¶
ToJavaArray converts go array in src to returned Java prim array object. Normally this method does not need to be called because New/Call/Field methods all call this internally.
type ExceptionHandler ¶
ExceptionHandler is used to convert a thrown exception (java.lang.Throwable) to a Go error.
var ( // DefaultExceptionHandler is an alias for DescribeExceptionHandler, which is the default. DefaultExceptionHandler = DescribeExceptionHandler // DescribeExceptionHandler calls the JNI exceptionDescribe function. DescribeExceptionHandler ExceptionHandler = ExceptionHandlerFunc(func(env *Env, exception *ObjectRef) error { exceptionDescribe(env.jniEnv) exceptionClear(env.jniEnv) return errors.New("Java exception occurred. check stderr/logcat") }) // ThrowableToStringExceptionHandler calls ToString on the exception and returns an error // with the returned value as its Error message. // If exception is nil or the toString() call fails, a generic default error is returned. ThrowableToStringExceptionHandler ExceptionHandler = ExceptionHandlerFunc(func(env *Env, exception *ObjectRef) error { exceptionClear(env.jniEnv) if exception.IsNil() { return errThrowableConvertFail } msg := "Java exception occurred" callStringMethodAndAssign(env, exception, "toString", func(s string) { if s == "" { return } msg = s }) return errors.New(msg) }) // ThrowableErrorExceptionHandler populates a new ThrowableError with the values of exception. // If exception is nil, the getClass().getName(), or the toString call fails, a generic default // error is returned. ThrowableErrorExceptionHandler ExceptionHandler = ExceptionHandlerFunc(func(env *Env, exception *ObjectRef) error { exceptionClear(env.jniEnv) if exception.IsNil() { return errThrowableConvertFail } throwableError, _ := NewThrowableErrorFromObject(env, exception) if throwableError == nil { return errThrowableConvertFail } return *throwableError }) )
type ExceptionHandlerFunc ¶
ExceptionHandlerFunc is an adapter to allow use of ordinary functions as an ExceptionHandler. If f is a function with the appropriate signature, ExceptionHandlerFunc(f) is an ExceptionHandler object that calls f.
func (ExceptionHandlerFunc) CatchException ¶
func (f ExceptionHandlerFunc) CatchException(env *Env, exception *ObjectRef) error
CatchException calls f to implement ExceptionHandler.
type JVM ¶
type JVM struct {
// contains filtered or unexported fields
}
JVM holds a JavaVM value, you only need one of these in your app.
func (*JVM) AttachCurrentThread ¶
AttachCurrentThread calls JNI AttachCurrentThread. Must call runtime.LockOSThread() first.
func (*JVM) DetachCurrentThread ¶
DetachCurrentThread calls JNI DetachCurrentThread, pass Env returned from AttachCurrentThread for current thread.
type JVMInitArgs ¶
type JVMInitArgs struct {
// contains filtered or unexported fields
}
JVMInitArgs holds a JavaVMInitArgs value
func NewJVMInitArgs ¶
func NewJVMInitArgs(ignoreUnrecognizedArgs bool, includeDefaultArgs bool, version int, args []string) *JVMInitArgs
NewJVMInitArgs builds JNI JavaVMInitArgs using GetDefaultJavaVMInitArgs and parameters.
type ObjectArrayType ¶
type ObjectArrayType string
ObjectArrayType is treated as Object | Array Type. It's value specify the class of the elements. Implements TypeSpec.
type ObjectRef ¶
type ObjectRef struct {
// contains filtered or unexported fields
}
ObjectRef holds a reference to a Java Object
func NewObjectArrayRef ¶
NewObjectArrayRef returns new *ObjectRef with Nil JNI object array reference and class name set to className.
func NewObjectRef ¶
NewObjectRef returns new *ObjectRef with Nil JNI object reference and class name set to className.
func WrapJObject ¶
WrapJObject wraps a JNI object value in an ObjectRef
func (*ObjectRef) CallMethod ¶
func (o *ObjectRef) CallMethod(env *Env, methodName string, dest interface{}, args ...interface{}) error
CallMethod calls method methodName on o with arguments args and stores return value in dest.
func (*ObjectRef) CallNonvirtualMethod ¶
func (o *ObjectRef) CallNonvirtualMethod(env *Env, className string, methodName string, dest interface{}, args ...interface{}) error
CallNonvirtualMethod calls non virtual method methodName on o with arguments args and stores return value in dest.
func (*ObjectRef) Cast ¶
Cast return a new *ObjectRef containing the receiver jobject and with class name set to className.
func (*ObjectRef) GetClassName ¶
GetClassName returns class name of object reference.
func (*ObjectRef) IsInstanceOf ¶
IsInstanceOf returns true if o is an instance of className
type ObjectType ¶
type ObjectType string
ObjectType is treated as Object Type. It's value is used to specify the class of the object. For example jnigi.ObjectType("java/lang/string"). Implements TypeSpec.
type StackTraceElement ¶
type StackTraceElement struct { ClassName string FileName string LineNumber int MethodName string IsNativeMethod bool AsString string }
StackTraceElement is a struct holding the contents of java.lang.StackTraceElement for use in a ThrowableError.
func NewStackTraceElementFromObject ¶
func NewStackTraceElementFromObject(env *Env, stackTraceElement *ObjectRef) (*StackTraceElement, error)
NewStackTraceElementFromObject creates a new StackTraceElement with its contents set from the values provided in stackTraceElement's methods.
func (StackTraceElement) String ¶
func (el StackTraceElement) String() string
type ThrowableError ¶
type ThrowableError struct { ClassName string LocalizedMessage string Message string StackTrace []StackTraceElement AsString string Cause *ThrowableError }
ThrowableError is an error struct that holds the relevant contents of a java.lang.Throwable. This is the returned error from ThrowableErrorExceptionHandler.
func NewThrowableErrorFromObject ¶
func NewThrowableErrorFromObject(env *Env, throwable *ObjectRef) (*ThrowableError, error)
NewThrowableErrorFromObject creates a new ThrowableError with its contents set from the values provided in throwable's methods.
func (ThrowableError) Error ¶
func (e ThrowableError) Error() string
func (ThrowableError) String ¶
func (e ThrowableError) String() string
type ToGoConverter ¶
type ToGoConverter interface { // Method should delete reference if it is not needed anymore ConvertToGo(obj *ObjectRef) error }
Types that can covert to Go values from object reference
type ToJavaConverter ¶
type ToJavaConverter interface { // Returned reference will be deleted ConvertToJava() (*ObjectRef, error) }
Types that can convert to Java Object
type Type ¶
type Type uint32
Type is used to specify return types and field types. Array value can be ORed with primitive type. Implements TypeSpec. See package constants for values.
type TypeGetter ¶
type TypeGetter interface {
GetType() Type
}
TypeGetter can be implemented to control which primitive type a value is treated as.