简体   繁体   English

如何获取Java类的所有公共静态方法?

[英]How do I get all public static methods of a class in Java?

clazz.getDeclaredMethods()将返回所有方法,但是我只想要那些public static方法,我该怎么做?

You need to check with the Modifier class after calling getModifiers on the Method objects 在对Method对象调用getModifiers之后,需要检查Modifier类。

public static void main(String[] args) throws Exception {   //Read user input into the array
    Method method = Main.class.getDeclaredMethod("main", String[].class);
    int modifiers = method.getModifiers();
    System.out.println(modifiers);

    System.out.println(Modifier.isStatic(modifiers));
    System.out.println(Modifier.isPublic(modifiers));
    System.out.println(Modifier.isAbstract(modifiers));
}

prints 版画

9
true
true
false

The int value holds information in specific bit positions for static , public , etc. modifiers. int值在staticpublic等修饰符的特定位位置保存信息。

you should iterate over the methods returned and check getModifiers() method. 您应该遍历返回的方法并检查getModifiers()方法。 If it returns STATIC or not. 是否返回STATIC。

More info in the javadoc javadoc中的更多信息

Try using: 尝试使用:

  Modifier.isStatic(method.getModifiers()).

Example: 例:

public static List<Method> getStaticMethods(Class<?> clazz) 
{
    List<Method> methods = new ArrayList<Method>();

    for (Method method : clazz.getMethods()) 
    {
        if (Modifier.isStatic(method.getModifiers())) 
        {
            methods.add(method);
        }
    }
    return Collections.unmodifiableList(methods);

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何获取Java类的公共方法然后运行它? - How get public methods of a java class and then run it? 如何从一个方法,另一个类的变量数据中读取公共静态变量并获取更新的数据 - How do I read in a public static, with variable data from a method, from another class and get updated data 如何在此类中使用公共变量和方法? - How do I use the public variables and methods in this class? Java:如何在静态方法中创建对象,还从另一个类调用方法? - Java: How do i create objects in a static method and also call for methods from another class? 我如何称呼另一个类中的公共静态void。 - How do I call a public static void that is in a different class. Java类,其所有方法都是静态的 - Java class which all its methods are static 为什么'Arrays'类'方法在Java中都是静态的? - Why are the 'Arrays' class' methods all static in Java? 如何在Python中执行与Java类似的公共静态声明? - How can I do this similar public static declarations to Java in Python? Java:是否需要同步所有静态方法? - Java: Do all static methods need to be synchronized? Java 反射:如何获取 java 类的所有 getter 方法并调用它们 - Java Reflection: How can I get the all getter methods of a java class and invoke them
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM