1. Overview
1.概述
In this quick tutorial, we’ll discuss how we can check if a method is static or not in Java by using the Reflection API.
在这个快速教程中,我们将讨论如何通过使用static,在Java中检查一个方法是否是反射API。
2. Example
2.例子
To demonstrate this, we’ll create StaticUtility class, with some static methods:
为了证明这一点,我们将创建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. Check if a Method Is static
3.检查一个方法是否为静态
We can check if a method is static or not by using the Modifier.isStatic method:
我们可以通过使用Modifier.isStatic方法来检查一个方法是否是静止的。。
@Test
void whenCheckStaticMethod_ThenSuccess() throws Exception {
Method method = StaticUtility.class.getMethod("getAuthorName", null);
Assertions.assertTrue(Modifier.isStatic(method.getModifiers()));
}
In the above example, we’ve first got the instance of the method which we want to test by using the Class.getMethod method. Once we have the method reference, all we need to do is just call the Modifier.isStatic method.
在上面的例子中,我们首先通过使用 Class.getMethod方法得到了我们要测试的方法的实例。一旦我们得到了方法引用,我们需要做的就是调用 Modifier.isStatic方法。
4. Get All static Methods of a Class
4.获取一个类的所有静态方法
Now that we already know how to check if a method is static or not, we can easily list all the static methods of a class:
现在我们已经知道如何检查一个方法是否是static,我们可以很容易地列出一个类的所有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());
}
In the above code, we’ve just verified the total number of static methods in our class StaticUtility.
在上面的代码中,我们刚刚验证了我们的类静态方法的总数StaticUtility。
5. Conclusion
5.总结
In this tutorial, we’ve seen how we can check if a method is static or not. We’ve also seen how to fetch all the static methods of a class as well.
在本教程中,我们已经看到了如何检查一个方法是否是static。我们还看到了如何获取一个类的所有static方法。
As always, the complete code for this example is available over on GitHub.
一如既往,本例的完整代码可在GitHub上获得over。