Determining if a method overrides another at runtime

后端 未结 1 1654
春和景丽
春和景丽 2021-02-07 19:08

I was wondering if there was any way to determine if a method represented by given java.lang.Method object overrides another methods represented by another ja

1条回答
  •  离开以前
    2021-02-07 19:48

    You can simply cross-check method names and signatures.

    public static boolean isOverriden(Method parent, Method toCheck) {
        if (parent.getDeclaringClass().isAssignableFrom(toCheck.getDeclaringClass())
                && parent.getName().equals(toCheck.getName())) {
             Class[] params1 = parent.getParameterTypes();
             Class[] params2 = toCheck.getParameterTypes();
             if (params1.length == params2.length) {
                 for (int i = 0; i < params1.length; i++) {
                     if (!params1[i].equals(params2[i])) {
                         return false;
                     }
                 }
                 return true;
             }
        }
        return false;
    }
    

    However, since your goal is to rename methods, you might instead wish to use a bytecode analysis/manipulation library such as ASM, where you can perform the same tests as well as easily modify the methods' names if the method returns true.

    0 讨论(0)
提交回复
热议问题