1. 概述

在本篇教程中,我们将介绍如何通过 Java 的 反射(Reflection) API 来判断一个方法是否是 static 方法。

2. 示例代码

为了演示方便,我们先定义一个 StaticUtility 类,并在里面写几个静态方法:

public class StaticUtility {

    public static String getAuthorName() {
        return "Umang Budhwar";
    }

    public static LocalDate getLocalDate() {
        return LocalDate.now();
    }

    public static LocalTime getLocalTime() {
        return LocalTime.now();
    }
}

3. 判断方法是否为 static

我们可以使用 Modifier.isStatic 方法来判断某个方法是否为静态方法。

示例代码如下:

@Test
void whenCheckStaticMethod_ThenSuccess() throws Exception {
    Method method = StaticUtility.class.getMethod("getAuthorName", null);
    Assertions.assertTrue(Modifier.isStatic(method.getModifiers()));
}

在这段代码中,我们首先通过 Class.getMethod 获取到目标方法的引用,然后调用 Modifier.isStatic 并传入该方法的修饰符信息进行判断。

⚠️ 注意:getMethod 的第二个参数是方法参数类型数组,如果方法没有参数可以传 null 或者空数组。

4. 获取类中所有 static 方法

既然已经知道如何判断单个方法是否为静态方法了,那获取整个类中的所有静态方法自然也不在话下:

@Test
void whenCheckAllStaticMethods_thenSuccess() {
    List<Method> methodList = Arrays.asList(StaticUtility.class.getMethods())
      .stream()
      .filter(method -> Modifier.isStatic(method.getModifiers()))
      .collect(Collectors.toList());
    Assertions.assertEquals(3, methodList.size());
}

这里我们使用了 Java 8 的 Stream 流式操作,从 getMethods() 返回的所有公共方法中筛选出所有静态方法,并验证数量是否为 3。

⚠️ 提醒:getMethods() 返回的是包括继承自父类和接口的 所有 public 方法,如果你只想获取当前类中声明的方法,应该使用 getDeclaredMethods()

5. 小结

在本教程中,我们学习了:

  • ✅ 如何利用反射判断某个方法是否是静态方法;
  • ✅ 如何批量获取一个类中所有的静态方法;

这些技巧虽然基础,但在编写通用工具、框架或做运行时逻辑判断时非常实用。

一如既往,本文完整示例代码可以在 GitHub 上找到。


原始标题:Checking if a Method Is Static Using Reflection in Java