Skip to content

io microsphere reflect MethodUtils

github-actions[bot] edited this page Jul 26, 2026 · 15 revisions

MethodUtils

Type: Class | Module: microsphere-java-core | Package: io.microsphere.reflect | Since: 1.0.0

Source: microsphere-java-core/src/main/java/io/microsphere/reflect/MethodUtils.java

Overview

The Java Reflection Method Utility class

Declaration

public abstract class MethodUtils implements Utils

Author: Mercy

Version Information

  • Introduced in: 1.0.0
  • Current Project Version: 0.3.16-SNAPSHOT

Version Compatibility

This component is tested and compatible with the following Java versions:

Java Version Status
Java 8 ✅ Compatible
Java 11 ✅ Compatible
Java 17 ✅ Compatible
Java 21 ✅ Compatible
Java 25 ✅ Compatible

Examples

Method Examples

initBannedMethods

System.setProperty(BANNED_METHODS_PROPERTY_NAME, "java.lang.String#substring() | java.lang.String#substring(int,int)")
Method method = MethodUtils.findMethod(String.class, "substring", int.class, int.class); // returns null
method = MethodUtils.findMethod(String.class, "substring"); // returns null
method = MethodUtils.findMethod(String.class, "substring", int.class); // returns non-null
System.setProperty(BANNED_METHODS_PROPERTY_NAME, "java.lang.String#substring() | java.lang.String#substring(int,int)")
Method method = MethodUtils.findMethod(String.class, "substring", int.class, int.class); // returns null
method = MethodUtils.findMethod(String.class, "substring"); // returns null
method = MethodUtils.findMethod(String.class, "substring", int.class); // returns non-null
// Set the system property to ban specific methods
System.setProperty(MethodUtils.BANNED_METHODS_PROPERTY_NAME,
    "java.lang.String#substring(int,int)|java.lang.Object#toString()");

// Initialize the banned methods cache
MethodUtils.initBannedMethods();

// After this call, findMethod will return null for banned methods
Method substringMethod = MethodUtils.findMethod(String.class, "substring", int.class, int.class);
// substringMethod will be null

banMethod

// Ban the String.substring(int, int) method
MethodUtils.banMethod(String.class, "substring", int.class, int.class);

// After this call, findMethod will return null for the banned method
Method method = MethodUtils.findMethod(String.class, "substring", int.class, int.class);
// method will be null

getDeclaredMethods

// Find all methods in MyClass excluding those declared by MySuperClass
List<Method> filteredMethods = MethodUtils.findMethods(MyClass.class,
    MethodUtils.excludedDeclaredClass(MySuperClass.class));
// Get all declared methods in MyClass
List<Method> declaredMethods = MethodUtils.getDeclaredMethods(MyClass.class);

getMethods

// Get all public methods declared in MyClass
List<Method> publicMethods = MethodUtils.getMethods(MyClass.class);

getAllDeclaredMethods

// Get all declared methods in MyClass, including inherited ones
List<Method> allDeclaredMethods = MethodUtils.getAllDeclaredMethods(MyClass.class);

getAllMethods

// Get all public methods of MyClass, including inherited ones
List<Method> allPublicMethods = MethodUtils.getAllMethods(MyClass.class);

findDeclaredMethods

// Get all declared methods in MyClass
List<Method> declaredMethods = MethodUtils.findDeclaredMethods(MyClass.class);
// Get all non-private declared methods in MyClass
List<Method> nonPrivateMethods = MethodUtils.findDeclaredMethods(MyClass.class,
    MethodUtils::isNonPrivate);

findMethods

// Get all public methods declared in MyClass
List<Method> publicMethods = MethodUtils.findMethods(MyClass.class);
// Get all non-static public methods declared in MyClass
List<Method> nonStaticPublicMethods = MethodUtils.findMethods(MyClass.class,
    method -> !MemberUtils.isStatic(method));

findAllDeclaredMethods

// Get all declared methods in MyClass
List<Method> declaredMethods = MethodUtils.findAllDeclaredMethods(MyClass.class);
// Get all non-private declared methods in MyClass
List<Method> nonPrivateMethods = MethodUtils.findAllDeclaredMethods(MyClass.class,
    method -> !MemberUtils.isPrivate(method));

findAllMethods

// Get all public methods of MyClass, including inherited ones
List<Method> allPublicMethods = MethodUtils.findAllMethods(MyClass.class);
// Get all non-static public methods of MyClass, including inherited ones
List<Method> nonStaticPublicMethods = MethodUtils.findAllMethods(MyClass.class,
    method -> !MemberUtils.isStatic(method));

findMethods

// Get all public methods of MyClass including inherited ones
List<Method> methods = MethodUtils.findMethods(MyClass.class, true, true);
// Get all non-static public methods of MyClass including inherited ones
List<Method> nonStaticPublicMethods = MethodUtils.findMethods(MyClass.class, true, true,
    method -> !MemberUtils.isStatic(method));
// Get all non-private, non-static methods of MyClass including inherited ones
List<Method> filteredMethods = MethodUtils.findMethods(MyClass.class, true, false,
    MethodUtils::isNonPrivate, MemberUtils::isNonStatic);

findMethod

// Find a method named "toString" in the MyClass class
Method method = MethodUtils.findMethod(MyClass.class, "toString");
if (method != null) {
    System.out.println("Method found: " + method);
} else {
    System.out.println("Method not found.");
}

findMethod

// Find a method named "toString" with no parameters in MyClass
Method method = MethodUtils.findMethod(MyClass.class, "toString");
if (method != null) {
    System.out.println("Method found: " + method);
} else {
    System.out.println("Method not found.");
}
// Find a method named "setValue" that takes a String parameter
Method method = MethodUtils.findMethod(MyClass.class, "setValue", String.class);
if (method != null) {
    System.out.println("Method found: " + method);
}

findDeclaredMethod

// Find a method named "exampleMethod" with no parameters
Method method1 = MethodUtils.findDeclaredMethod(MyClass.class, "exampleMethod");
// Find a method named "exampleMethod" that takes a String and an int
Method method2 = MethodUtils.findDeclaredMethod(MyClass.class, "exampleMethod", String.class, int.class);

invokeMethod

// Example class with an instance method
public class MyClass {
    public String greet(String name) {
        return "Hello, " + name;
    }
}

// Create an instance of MyClass
MyClass myInstance = new MyClass();

// Call the 'greet' method using invokeMethod
String result = MethodUtils.invokeMethod(myInstance, "greet", "World");
System.out.println(result);  // Output: Hello, World

invokeMethod

class User {
    private String secret() {
        return "hidden";
    }
}

User user = new User();
String value = MethodUtils.invokeMethod(true, user, "secret");
System.out.println(value); // Output: hidden

invokeMethod

public class ExampleClass {
    public String greet(String name) {
        return "Hello, " + name;
    }
}

// Create an instance of ExampleClass
ExampleClass exampleInstance = new ExampleClass();

// Call the 'greet' method using invokeMethod
String result = MethodUtils.invokeMethod(exampleInstance, ExampleClass.class, "greet", "World");
System.out.println(result);  // Output: Hello, World

invokeMethod

class BaseService {
    protected String ping(String name) {
        return "pong " + name;
    }
}

BaseService service = new BaseService();
String result = MethodUtils.invokeMethod(service, true, BaseService.class, "ping", "Microsphere");
System.out.println(result); // Output: pong Microsphere

invokeStaticMethod

public class ExampleClass {
    public static int add(int a, int b) {
        return a + b;
    }
}

// Invoke the static method "add"
Integer result = MethodUtils.invokeStaticMethod(ExampleClass.class, "add", 2, 3);
System.out.println(result);  // Output: 5

invokeStaticMethod

class SecretMath {
    private static int sum(int a, int b) {
        return a + b;
    }
}

Integer value = MethodUtils.invokeStaticMethod(true, SecretMath.class, "sum", 1, 2);
System.out.println(value); // Output: 3

Usage

Maven Dependency

Add the following dependency to your pom.xml:

<dependency>
    <groupId>io.github.microsphere-projects</groupId>
    <artifactId>microsphere-java-core</artifactId>
    <version>${microsphere-java.version}</version>
</dependency>

Tip: Use the BOM (microsphere-java-dependencies) for consistent version management. See the Getting Started guide.

Import

import io.microsphere.reflect.MethodUtils;

API Reference

Public Methods

Method Description
initBannedMethods The prefix of the "GETTER" method name : "get"
banMethod Bans method to the cache based on the provided class, method name, and parameter types.
getDeclaredMethods Creates a Predicate that excludes methods declared by the specified class.
getMethods Get all public Method methods of the target class, excluding the inherited methods.
getAllDeclaredMethods Get all declared Method methods of the target class, including the inherited methods.
getAllMethods Get all public Method methods of the target class, including the inherited methods.
findDeclaredMethods Find all declared Method methods of the target class, excluding the inherited methods.
findMethods Find all public methods directly declared in the specified class, without including inherited methods.
findAllDeclaredMethods Retrieves all declared methods directly defined in the specified class, excluding inherited methods.
findAllMethods Get all public Method methods of the target class, including the inherited methods.
findMethods Find all Method methods of the target class by the specified criteria.
findMethod Find the Method by the specified type (including inherited types) and method name without the
findMethod Find the Method by the specified type (including inherited types), method name, and parameter types.
findDeclaredMethod Finds a declared method in the specified class, including its superclasses and interfaces.
invokeMethod Invokes a method with the specified name on the given object, using the provided arguments.
invokeMethod Invokes a method with the specified name on the given object, optionally forcing accessibility.
invokeMethod Invokes a method with the specified name on the given class type, using the provided arguments.
invokeMethod Invokes a method by name on the specified type, optionally forcing accessibility.
invokeStaticMethod Invokes a static method of the specified target class with the given method name and arguments.
invokeStaticMethod Invokes a static method of the specified class by name, with optional forced accessibility.

Method Details

initBannedMethods

public static void initBannedMethods()

The prefix of the "GETTER" method name : "get" / public static final String GET_METHOD_NAME_PREFIX = "get";

/** The prefix of the "SETTER" method name : "set" / public static final String SET_METHOD_NAME_PREFIX = "set";

/** The prefix of the "IS" method name : "is" / public static final String IS_METHOD_NAME_PREFIX = "is";

/** The property name of banned methods : "microsphere.reflect.banned-methods"

Example Usage

`System.setProperty(BANNED_METHODS_PROPERTY_NAME, "java.lang.String#substring() | java.lang.String#substring(int,int)")
Method method = MethodUtils.findMethod(String.class, "substring", int.class, int.class); // returns null
method = MethodUtils.findMethod(String.class, "substring"); // returns null
method = MethodUtils.findMethod(String.class, "substring", int.class); // returns non-null
`

/

banMethod

public static Method banMethod(@Nonnull Class<?> declaredClass, @Nonnull String methodName, @Nonnull Class<?>... parameterTypes)

Bans method to the cache based on the provided class, method name, and parameter types.

This method creates a MethodKey using the specified parameters, finds the corresponding Method using #doFindMethod(MethodKey), and stores it in the #bannedMethodsCache. If the method is already present in the cache, it will not be overwritten.

Example Usage

`// Ban the String.substring(int, int) method
MethodUtils.banMethod(String.class, "substring", int.class, int.class);

// After this call, findMethod will return null for the banned method
Method method = MethodUtils.findMethod(String.class, "substring", int.class, int.class);
// method will be null
`

getDeclaredMethods

public static List<Method> getDeclaredMethods(@Nullable Class<?> targetClass)

Creates a Predicate that excludes methods declared by the specified class.

This method is useful when filtering methods to exclude those that are declared by a specific class, for example, when searching for overridden methods in subclasses.

Example Usage

`// Find all methods in MyClass excluding those declared by MySuperClass
List filteredMethods = MethodUtils.findMethods(MyClass.class,
    MethodUtils.excludedDeclaredClass(MySuperClass.class));
`

getMethods

public static List<Method> getMethods(@Nullable Class<?> targetClass)

Get all public Method methods of the target class, excluding the inherited methods.

This method retrieves only the public methods that are directly declared in the specified class, without including any methods from its superclasses or interfaces.

Example Usage

`// Get all public methods declared in MyClass
List publicMethods = MethodUtils.getMethods(MyClass.class);
`

getAllDeclaredMethods

public static List<Method> getAllDeclaredMethods(@Nullable Class<?> targetClass)

Get all declared Method methods of the target class, including the inherited methods.

This method retrieves all methods that are declared in the specified class and its superclasses, including those from interfaces implemented by the class and its ancestors.

Example Usage

`// Get all declared methods in MyClass, including inherited ones
List allDeclaredMethods = MethodUtils.getAllDeclaredMethods(MyClass.class);
`

getAllMethods

public static List<Method> getAllMethods(@Nullable Class<?> targetClass)

Get all public Method methods of the target class, including the inherited methods.

This method retrieves all public methods that are declared in the specified class and its superclasses, including those from interfaces implemented by the class and its ancestors.

Example Usage

`// Get all public methods of MyClass, including inherited ones
List allPublicMethods = MethodUtils.getAllMethods(MyClass.class);
`

Note: If you need only the methods declared directly in the class (excluding inherited ones), consider using #getMethods(Class) instead.

findDeclaredMethods

public static List<Method> findDeclaredMethods(@Nullable Class<?> targetClass, @Nullable Predicate<? super Method>... methodsToFilter)

Find all declared Method methods of the target class, excluding the inherited methods.

This method retrieves only the methods that are directly declared in the specified class, without including any methods from its superclasses or interfaces.

Example Usage

`// Get all declared methods in MyClass
List declaredMethods = MethodUtils.findDeclaredMethods(MyClass.class);
`

Filtering Example

`// Get all non-private declared methods in MyClass
List nonPrivateMethods = MethodUtils.findDeclaredMethods(MyClass.class,
    MethodUtils::isNonPrivate);
`

findMethods

public static List<Method> findMethods(@Nullable Class<?> targetClass, @Nullable Predicate<? super Method>... methodsToFilter)

Find all public methods directly declared in the specified class, without including inherited methods.

This method retrieves only the public methods that are explicitly declared in the given class, excluding any methods from its superclasses or interfaces.

Example Usage

`// Get all public methods declared in MyClass
List publicMethods = MethodUtils.findMethods(MyClass.class);
`

Filtering Example

`// Get all non-static public methods declared in MyClass
List nonStaticPublicMethods = MethodUtils.findMethods(MyClass.class,
    method -> !MemberUtils.isStatic(method));
`

findAllDeclaredMethods

public static List<Method> findAllDeclaredMethods(@Nullable Class<?> targetClass, @Nullable Predicate<? super Method>... methodsToFilter)

Retrieves all declared methods directly defined in the specified class, excluding inherited methods.

This method returns only the methods that are explicitly declared in the given class, and does not include any methods from superclasses or interfaces.

Example Usage

`// Get all declared methods in MyClass
List declaredMethods = MethodUtils.findAllDeclaredMethods(MyClass.class);
`

Filtering Example

`// Get all non-private declared methods in MyClass
List nonPrivateMethods = MethodUtils.findAllDeclaredMethods(MyClass.class,
    method -> !MemberUtils.isPrivate(method));
`

findAllMethods

public static List<Method> findAllMethods(@Nullable Class<?> targetClass, @Nullable Predicate<? super Method>... methodsToFilter)

Get all public Method methods of the target class, including the inherited methods.

This method retrieves all public methods that are declared in the specified class and its superclasses, including those from interfaces implemented by the class and its ancestors.

Example Usage

`// Get all public methods of MyClass, including inherited ones
List allPublicMethods = MethodUtils.findAllMethods(MyClass.class);
`

Filtering Example

`// Get all non-static public methods of MyClass, including inherited ones
List nonStaticPublicMethods = MethodUtils.findAllMethods(MyClass.class,
    method -> !MemberUtils.isStatic(method));
`

findMethods

public static List<Method> findMethods(@Nullable Class<?> targetClass, boolean includeInheritedTypes, boolean publicOnly,
                                           @Nullable Predicate<? super Method>... methodsToFilter)

Find all Method methods of the target class by the specified criteria.

This method provides a flexible way to retrieve methods from a class based on whether inherited methods should be included, whether only public methods should be considered, and optional filtering predicates.

Example Usage

Basic Usage

`// Get all public methods of MyClass including inherited ones
List methods = MethodUtils.findMethods(MyClass.class, true, true);
`

Filtering Example

`// Get all non-static public methods of MyClass including inherited ones
List nonStaticPublicMethods = MethodUtils.findMethods(MyClass.class, true, true,
    method -> !MemberUtils.isStatic(method));
`

Advanced Filtering Example

`// Get all non-private, non-static methods of MyClass including inherited ones
List filteredMethods = MethodUtils.findMethods(MyClass.class, true, false,
    MethodUtils::isNonPrivate, MemberUtils::isNonStatic);
`

findMethod

public static Method findMethod(@Nullable Class targetClass, @Nullable String methodName)

Find the Method by the specified type (including inherited types) and method name without the parameter type.

This method searches for a method with the given name in the specified class and its superclasses, returning the first match found. If no method is found, this method returns null.

Example Usage

`// Find a method named "toString" in the MyClass class
Method method = MethodUtils.findMethod(MyClass.class, "toString");
if (method != null) {
    System.out.println("Method found: " + method);
` else {
    System.out.println("Method not found.");
}
}

findMethod

public static Method findMethod(@Nullable Class targetClass, @Nullable String methodName, @Nullable Class<?>... parameterTypes)

Find the Method by the specified type (including inherited types), method name, and parameter types.

This method searches for a method with the given name and parameter types in the specified class and its superclasses, returning the first match found. The search is cached to improve performance on repeated calls. If no matching method is found, this method returns null.

Example Usage

`// Find a method named "toString" with no parameters in MyClass
Method method = MethodUtils.findMethod(MyClass.class, "toString");
if (method != null) {
    System.out.println("Method found: " + method);
` else {
    System.out.println("Method not found.");
}
}
`// Find a method named "setValue" that takes a String parameter
Method method = MethodUtils.findMethod(MyClass.class, "setValue", String.class);
if (method != null) {
    System.out.println("Method found: " + method);
`
}

findDeclaredMethod

public static Method findDeclaredMethod(@Nullable Class<?> targetClass, @Nullable String methodName, @Nullable Class<?>... parameterTypes)

Finds a declared method in the specified class, including its superclasses and interfaces.

This method searches for a method with the given name and parameter types in the specified class, its superclasses (if the class is not an interface), and its implemented interfaces. It returns the first matching method found.

Example Usage

`// Find a method named "exampleMethod" with no parameters
Method method1 = MethodUtils.findDeclaredMethod(MyClass.class, "exampleMethod");
`
`// Find a method named "exampleMethod" that takes a String and an int
Method method2 = MethodUtils.findDeclaredMethod(MyClass.class, "exampleMethod", String.class, int.class);
`

invokeMethod

public static <R> R invokeMethod(@Nonnull Object object, @Nonnull String methodName, @Nonnull Object... arguments)

Invokes a method with the specified name on the given object, using the provided arguments.

This method dynamically retrieves the class of the target object and searches for the appropriate method to invoke based on the method name and argument types. It supports both instance and static methods.

Example Usage

`// Example class with an instance method
public class MyClass {
    public String greet(String name) {
        return "Hello, " + name;
    `
}

// Create an instance of MyClass
MyClass myInstance = new MyClass();

// Call the 'greet' method using invokeMethod
String result = MethodUtils.invokeMethod(myInstance, "greet", "World");
System.out.println(result);  // Output: Hello, World
}

Note: This method internally uses reflection to find and invoke the matching method, which may throw exceptions if the method cannot be found or invoked properly.

invokeMethod

public static <R> R invokeMethod(boolean forceAccess, @Nonnull Object object, @Nonnull String methodName, @Nonnull Object... arguments)

Invokes a method with the specified name on the given object, optionally forcing accessibility.

When forceAccess is true, this method allows invocation of non-public methods by setting accessible flag before invoking.

Example Usage

`class User {
    private String secret() {
        return "hidden";
    `
}

User user = new User();
String value = MethodUtils.invokeMethod(true, user, "secret");
System.out.println(value); // Output: hidden
}

invokeMethod

public static <R> R invokeMethod(@Nonnull Object object, @Nonnull Class<?> type, @Nonnull String methodName, @Nonnull Object... arguments)

Invokes a method with the specified name on the given class type, using the provided arguments.

This method dynamically searches for a method in the specified class that matches the method name and argument types, and then invokes it. It supports both instance and static methods.

Example Usage

`public class ExampleClass {
    public String greet(String name) {
        return "Hello, " + name;
    `
}

// Create an instance of ExampleClass
ExampleClass exampleInstance = new ExampleClass();

// Call the 'greet' method using invokeMethod
String result = MethodUtils.invokeMethod(exampleInstance, ExampleClass.class, "greet", "World");
System.out.println(result);  // Output: Hello, World
}

Note: This method internally uses reflection to find and invoke the matching method, which may throw exceptions if the method cannot be found or invoked properly.

invokeMethod

public static <R> R invokeMethod(@Nonnull Object object, boolean forceAccess, @Nonnull Class<?> type, @Nonnull String methodName, @Nonnull Object... arguments)

Invokes a method by name on the specified type, optionally forcing accessibility.

This overload is useful when the invocation target is represented by a super type or interface, or when private/protected methods need to be accessed via reflection.

Example Usage

`class BaseService {
    protected String ping(String name) {
        return "pong " + name;
    `
}

BaseService service = new BaseService();
String result = MethodUtils.invokeMethod(service, true, BaseService.class, "ping", "Microsphere");
System.out.println(result); // Output: pong Microsphere
}

invokeStaticMethod

public static <R> R invokeStaticMethod(@Nonnull Class<?> targetClass, @Nonnull String methodName, @Nonnull Object... arguments)

Invokes a static method of the specified target class with the given method name and arguments.

This utility method simplifies the process of invoking a static method using reflection by internally calling #invokeMethod(Object, Class, String, Object...) with a null instance to indicate that the method is static.

Example Usage

`public class ExampleClass {
    public static int add(int a, int b) {
        return a + b;
    `
}

// Invoke the static method "add"
Integer result = MethodUtils.invokeStaticMethod(ExampleClass.class, "add", 2, 3);
System.out.println(result);  // Output: 5
}

invokeStaticMethod

public static <R> R invokeStaticMethod(boolean forceAccess, @Nonnull Class<?> targetClass, @Nonnull String methodName, @Nonnull Object... arguments)

Invokes a static method of the specified class by name, with optional forced accessibility.

When forceAccess is true, this method attempts to make the target method accessible before invocation, allowing reflective access to non-public static methods.

Example Usage

`class SecretMath {
    private static int sum(int a, int b) {
        return a + b;
    `
}

Integer value = MethodUtils.invokeStaticMethod(true, SecretMath.class, "sum", 1, 2);
System.out.println(value); // Output: 3
}

This documentation was auto-generated from the source code of microsphere-java.

Home

annotation-processor

java-annotations

java-core

java-test

jdk-tools

lang-model

Clone this wiki locally