java如何知道一个方法被重写了,Java:如何查找是否从基类重写了一个方法?

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

For example,

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());

}

}

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

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.

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?"

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.

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.

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值