Getting a list of accessible methods for a given class via reflection

前端 未结 4 1776
你的背包
你的背包 2020-12-02 20:32

Is there a way to get a list of methods that would be accessible (not necessarily public) by a given class? The code in question will be in a completely different class.

4条回答
  •  执笔经年
    2020-12-02 21:03

    As cletus and PSpeed has already answered - you need to traverse the inheritance tree of classes.

    This is the way I do it, but without handling package private methods:

    public static Method[] getAccessibleMethods(Class clazz) {
       List result = new ArrayList();
    
       while (clazz != null) {
          for (Method method : clazz.getDeclaredMethods()) {
             int modifiers = method.getModifiers();
             if (Modifier.isPublic(modifiers) || Modifier.isProtected(modifiers)) {
                result.add(method);
             }
          }
          clazz = clazz.getSuperclass();
       }
    
       return result.toArray(new Method[result.size()]);
    }
    

    I am using it in a backwards-compatibility checker where I know that the classes that might be affected will not be in the same package anyway.

提交回复
热议问题