Determining if a method overrides another at runtime

时光怂恿深爱的人放手 提交于 2019-12-04 10:23:37

问题


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 java.lang.Method object?

I'm working on Stronlgy typed javascript, and I need to be able to be able to know if a method overrides another one in order to be able to rename both of them to a shorter name.

In this case, I am talking about the extended definition of overriding, as supported by the @Override annotation, which includes implementation of interface and abstract class methods.

I'd be happy with any solution involving either reflection directly, or using any library that already does this.


回答1:


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.



来源:https://stackoverflow.com/questions/12133817/determining-if-a-method-overrides-another-at-runtime

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!