Java:如何查找是否从基类重写了一个方法? [英] Java: How to find if a method is overridden from base class?

查看:134
本文介绍了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的实例,如何我知道是否有任何派生类重写了方法m(),如B2?

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,我怎么知道任何派生类是否有覆盖方法m()如B2?

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目录,也许您应该查看该路由。

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天全站免登陆