How can I check if a method is static using reflection?

后端 未结 3 1964
忘了有多久
忘了有多久 2021-01-30 12:32

I want to discover at run-time ONLY the static Methods of a class, how can I do this? Or, how to differentiate between static and non-static methods.

3条回答
  •  -上瘾入骨i
    2021-01-30 12:44

    To flesh out the previous (correct) answer, here is a full code snippet which does what you want (exceptions ignored):

    public Method[] getStatics(Class c) {
        Method[] all = c.getDeclaredMethods()
        List back = new ArrayList();
    
        for (Method m : all) {
            if (Modifier.isStatic(m.getModifiers())) {
                back.add(m);
            }
        }
    
        return back.toArray(new Method[back.size()]);
    }
    

提交回复
热议问题