Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

MethodType — describing parameter and return types

java.lang.invoke.MethodType describes a method handle's return type and ordered parameter types. The MethodType.methodType factory creates this immutable description.

Version: Java SE 21; repository runtime, production runtime not attested

Syntax

MethodType.methodType(returnType, parameterType0, ...)
MethodType.methodType(returnType)

java.lang.invoke provides method handles (MethodHandle) and dynamic invocation mechanisms. MethodType describes invocation types, not the executed method's code or name.

In MethodType.methodType(int.class, String.class), the first argument specifies the return type and the remaining arguments specify parameter types in order. MethodType.methodType(void.class) describes an invocation with no parameters and no result. void.class cannot be a parameter type; null values are also prohibited.

Instances are immutable: changeReturnType returns a description with a changed return type without modifying the original. Compare descriptions using equals, not ==; instance caching is not guaranteed. In the example, (String)int means one String parameter and an int result.

Examples

import java.lang.invoke.MethodType;

public class Main {
    public static void main(String[] args) {
        MethodType type = MethodType.methodType(int.class, String.class);
        MethodType changed = type.changeReturnType(long.class);

        System.out.println(type);
        System.out.println(changed);
        System.out.println(type.equals(
                MethodType.methodType(int.class, String.class)));
    }
}

Result

(String)int
(String)long
true

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources