确定方法是否在运行时覆盖另一个方法 [英] Determining if a method overrides another at runtime

查看:178
本文介绍了确定方法是否在运行时覆盖另一个方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否有办法确定给定 java.lang.Method 对象所代表的方法是否会覆盖另一个表示的另一个方法java.lang.Method object?

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?

我正在研究 Stronlgy类型的javascript ,我需要能够知道一个方法是否覆盖了另一个方法,以便能够将它们重命名为更短的名称。

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.

在这种情况下,我说的是覆盖的扩展定义,由 @Override 注释支持,其中包括接口和抽象的实现类方法。

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.

推荐答案

您可以简单地交叉检查方法名称和签名。

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;
}

但是,由于您的目标是重命名方法,您可能希望使用字节码分析/操作库,例如 ASM ,您可以在其中执行相同的测试以及轻松修改方法'如果方法返回true,则命名。

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.

这篇关于确定方法是否在运行时覆盖另一个方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆