Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

native — method outside Java

native — method outside Java: The native modifier declares a method implemented outside the Java language; the declaration ends with a semicolon and has no Java body.

Version: Java SE 21 (JLS and Java SE API); examples verified on the repository Java runtime

Syntax

native

The native modifier declares a method implemented outside the Java language; the declaration ends with a semicolon and has no Java body.

Use native only at a narrow controlled JNI or runtime boundary and hide it behind a safe Java API that validates data.

If an implementation is missing, UnsatisfiedLinkError may occur when the method is used or earlier, depending on JVM resolution timing; its signature must match native code.

A native method may be static or instance and is visible through reflection; the example inspects the modifier but deliberately does not invoke it.

Reflection finds the uninvoked add method; Modifier.isNative produces native=true, and the method return type produces return=int.

Examples

import java.lang.reflect.Method;
import java.lang.reflect.Modifier;

public class Main {
    private static native int add(int left, int right);

    public static void main(String[] args) throws Exception {
        Method method = Main.class.getDeclaredMethod("add", int.class, int.class);
        System.out.println("native=" + Modifier.isNative(method.getModifiers()));
        System.out.println("return=" + method.getReturnType().getSimpleName());
    }
}

Result

native=true
return=int

Reflection finds the uninvoked add method; Modifier.isNative produces native=true, and the method return type produces return=int.

Sources