java使用旧签名类,Java如何使用相同的名称/签名区分这些多个方法?

I was tracking down a bug today, and I noticed something strange within one of our classes. I cut out as much code as possible to post here:

class A {

static int obtainNumber() { return 42; }

static int obtainNumber() { return 3; }

static int obtainNumber() { return -1; }

static {

System.out.println(obtainNumber());

}

}

This class has 3 methods with the exact same name and signature. At first I thought this was invalid code, but then eclipse would have highlighted the code in red. It does work:

javac A.java && java A

42

Exception in thread "main" java.lang.NoSuchMethodError: main

So I figured maybe Java will just use the first one it sees. I reordered to test:

class A {

static int obtainNumber() { return 3; }

static int obtainNumber() { return -1; }

static int obtainNumber() { return 42; }

static {

System.out.println(obtainNumber());

}

}

Nope, same result:

javac A.java && java A

42

Exception in thread "main" java.lang.NoSuchMethodError: main

I thought perhaps it uses the one with 42 because its the biggest. To test this, I took the original and changed the return values:

class A {

static int obtainNumber() { return 0; }

static int obtainNumber() { return 1; }

static int obtainNumber() { return 2; }

static {

System.out.println(obtainNumber());

}

}

It still knows to use the first one:

javac A.java && java A

0

Exception in thread "main" java.lang.NoSuchMethodError: main

And if I reorder them again:

class A {

static int obtainNumber() { return 1; }

static int obtainNumber() { return 0; }

static int obtainNumber() { return 2; }

static {

System.out.println(obtainNumber());

}

}

Same result:

javac A.java && java A

0

Exception in thread "main" java.lang.NoSuchMethodError: main

I thought Java was a text based language, which I'd expect makes this sort of thing impossible. How is Java tracking which method is which?

解决方案

Hidden characters. The source code is equivalent to

static int obtainNumber() { return 42; }

static int obtain\ufeffNumber() { return 3; }

static int obtain\ufeff\ufeffNumber() { return -1; }

To avoid this kind of problems, my source files are strictly US-ASCII. I want to be certain that the characters I see are exactly the characters compiler sees.

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值