Skip to content

io microsphere reflect MethodUtils

github-actions[bot] edited this page Mar 21, 2026 · 1 revision

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.1.10-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

clearBannedMethods

// Clear all banned methods
MethodUtils.clearBannedMethods();

// After this call, findMethod will return previously banned methods
Method method = MethodUtils.findMethod(String.class, "substring", int.class, int.class);
// method may now be non-null if it was previously banned

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

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

public class ExampleClass {
    public static int multiply(int a, int b) {
        return a * b;
    }
}

// Retrieve the method using reflection
Method method = ExampleClass.class.getMethod("multiply", int.class, int.class);

// Invoke the static method
Integer result = MethodUtils.invokeStaticMethod(method, 5, 3);
System.out.println(result);  // Output: 15

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

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

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

// Instance method example
ExampleClass instance = new ExampleClass();
String result = MethodUtils.invokeMethod(instance, ExampleClass.class.getMethod("greet", String.class), "World");
System.out.println(result); // Output: Hello, World

// Static method example
Integer sum = MethodUtils.invokeMethod(null, ExampleClass.class.getMethod("add", int.class, int.class), 2, 3);
System.out.println(sum); // Output: 5

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.
clearBannedMethods Clears the cache of banned methods.
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.
invokeStaticMethod Invokes a static method of the specified target class with the given method name and arguments.
invokeStaticMethod Invokes the specified static method represented by the given Method object.
invokeMethod Invokes a method with the specified name on the given class type, using the provided arguments.
invokeMethod Invokes the underlying method represented by this Method

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
`

/ public static final String BANNED_METHODS_PROPERTY_NAME = MICROSPHERE_PROPERTY_NAME_PREFIX + "reflect.banned-methods";

/** The public methods of Object /

banMethod

public static Method banMethod(Class<?> declaredClass, String methodName, 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
`

clearBannedMethods

public static void clearBannedMethods()

Clears the cache of banned methods.

This method removes all entries from the #bannedMethodsCache, effectively allowing all previously banned methods to be discoverable again by #findMethod(Class, String, Class[]).

Example Usage

`// Clear all banned methods
MethodUtils.clearBannedMethods();

// After this call, findMethod will return previously banned methods
Method method = MethodUtils.findMethod(String.class, "substring", int.class, int.class);
// method may now be non-null if it was previously banned
`

getDeclaredMethods

public static List<Method> getDeclaredMethods(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(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(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(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(Class<?> targetClass, 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(Class<?> targetClass, 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(Class<?> targetClass, 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(Class<?> targetClass, 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(Class<?> targetClass, boolean includeInheritedTypes, boolean publicOnly,
                                           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(Class targetClass, 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(Class targetClass, String methodName, 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(Class<?> targetClass, String methodName, 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(Object object, String methodName, 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.

invokeStaticMethod

public static <R> R invokeStaticMethod(Class<?> targetClass, String methodName, 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(Method method, Object... arguments)

Invokes the specified static method represented by the given Method object.

This method is specifically designed to invoke static methods. If the provided method is not static, it may result in an exception during invocation.

Example Usage

`public class ExampleClass {
    public static int multiply(int a, int b) {
        return a * b;
    `
}

// Retrieve the method using reflection
Method method = ExampleClass.class.getMethod("multiply", int.class, int.class);

// Invoke the static method
Integer result = MethodUtils.invokeStaticMethod(method, 5, 3);
System.out.println(result);  // Output: 15
}

invokeMethod

public static <R> R invokeMethod(Object instance, Class<?> type, String methodName, 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(@Nullable Object instance, Method method, Object... arguments)

Invokes the underlying method represented by this Method object, on the specified object with the specified parameters. Individual parameters are automatically unwrapped to match primitive formal parameters, and both primitive and reference parameters are subject to method invocation conversions as necessary.

If the underlying method is static, then the specified instance argument is ignored. It may be null.

If the number of formal parameters required by the underlying method is 0, the supplied args array may be of length 0 or null.

If the underlying method is an instance method, it is invoked using dynamic method lookup as documented in The Java Language Specification, section {@jls 15.12.4.4}; in particular, overriding based on the runtime type of the target object may occur.

If the underlying method is static, the class that declared the method is initialized if it has not already been initialized.

If the method completes normally, the value it returns is returned to the caller of invoke; if the value has a primitive type, it is first appropriately wrapped in an object. However, if the value has the type of an array of a primitive type, the elements of the array are not wrapped in objects; in other words, an array of primitive type is returned. If the underlying method return type is void, the invocation returns null.

Example Usage

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

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

// Instance method example
ExampleClass instance = new ExampleClass();
String result = MethodUtils.invokeMethod(instance, ExampleClass.class.getMethod("greet", String.class), "World");
System.out.println(result); // Output: Hello, World

// Static method example
Integer sum = MethodUtils.invokeMethod(null, ExampleClass.class.getMethod("add", int.class, int.class), 2, 3);
System.out.println(sum); // Output: 5
}

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

Home

java-annotations

java-core

jdk-tools

lang-model

annotation-processor

java-test

Clone this wiki locally