Java:如何查找方法是否被基类覆盖? [英] Java: How to find if a method is overridden from base class?

查看:30
本文介绍了Java:如何查找方法是否被基类覆盖?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何确定一个方法是否被子类覆盖?

How to find out if a method is overridden by child classes?

例如

public class Test {

static public class B {
    public String m() {return "From B";};
}

static public class B1 extends B {

}

static public class B2 extends B {
    public String m() {return "from B2";};
}

/**
 * @param args
 * @throws FileNotFoundException 
 */
public static void main(String[] args)  {

    B b1 = new B1();
    System.out.println("b1 = " + b1.m());
    B b2 = new B2();
    System.out.println("b1 = " + b2.m());
}

}

给定一个 B 的实例,我如何知道是否有任何派生类像 B2 那样重写了方法 m()?

Given an instance of B, how do I know if any derived classes have overridden method m() like B2?

更新:我的问题不清楚.实际上,我试图在不诉诸反思的情况下询问这是否可行.这项检查是在一个紧密循环中完成的,它用于性能黑客以节省几个 CPU 周期.

Update: My question wasn't clear. Actually, I was trying to ask if this is possible without resorting to reflection. This check is done in a tight loop and it's used in a performance hack to save a few CPU cycles.

推荐答案

我认为目前的答案是假设您有一个方法,并且正在尝试确定该方法是否在类中被覆盖.

I think the answers so far are assuming that you have a method and are trying to determine whether that method is overridden in a class.

然而,实际提出的问题是给定一个 B 的实例,我如何知道是否有任何派生类像 B2 一样重写了方法 m()?"

However, the actual question asked was "Given an instance of B, how do I know if any derived classes have overridden method m() like B2?"

使用标准 Java 方法无法做到这一点,因为 Java 在类被引用之前不会加载它们.例如,假设您有一个从网络上的 jar(或多个 jar)加载的 URL 类加载器.Java 不知道那些联网的 jar 文件中包含哪些类,更不用说它们是否碰巧覆盖了特定的方法.

This is not possible to do using standard Java methodology, because Java does not load classes until they are referenced. For example, assume you have a URL classloader loading from a jar (or many jars) on the network. Java has no idea what classes are contained in those networked jar files, let alone whether they happen to override a particular method.

我认为我已经看到 Apache 公共资源中的实用程序会尝试彻底搜索类加载器的层次结构以组装所有可用类的列表,但这对我来说听起来很糟糕.一方面,它会触发 JVM 中每个类的每个静态初始化块.

I think that I've seen utilities in Apache commons that will try to exhaustively search the hierarchy of classloaders to assemble a list of all available classes, but this sounds like a pretty bad idea to me. For one thing, it will trigger every single static initializer block for every class in the JVM.

在jar的META-INF目录下有一些工具,比如Service Provider Interface,可以列出实现某个接口的类名,也许你应该看看那个路由.

There are some facilities like the Service Provider Interface to list class names in the jar's META-INF directory that implement a certain interface, maybe you should look at that route.

这篇关于Java:如何查找方法是否被基类覆盖?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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