Java:为什么.class文件中的方法类型包含返回类型,而不仅是签名? [英] Java: Why method type in .class file contains return type, not only signature?

查看:84
本文介绍了Java:为什么.class文件中的方法类型包含返回类型,而不仅是签名?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

.class文件中的常量池中有一个"NameAndType"结构. 它用于动态绑定. 该类可以导出"的所有方法都称为签名+返回类型". 像

There is a "NameAndType" structure in the constants pool in .class file. It is used for dynamic binding. All methods that class can "export" described as "signature + return type". Like

"getVector()Ljava/util/Vector;"

当某些.jar中的方法的返回类型更改时,即使新类型更窄,这也会破坏我的代码.

That breakes my code when return type of the method in some .jar is changed, even if new type is narrower.

即: 我有以下代码:

List l = some.getList();

外部.jar包含:

public List getList()

比外部jar将方法签名更改为

Than external jar changes method signature to

public ArrayList getList().

我的代码在运行时因NoSuchMethodException而死,因为找不到它

And my code dies in run-time with NoSuchMethodException, because it can't find

getList()Ljava/util/List;

因此,我必须重新编译我的代码. 我不必更改它.只需重新编译完全相同的代码即可!

So, I have to recompile my code. I do not have to change it. Just recompile absolutely the same code!

这还使您能够拥有两种带有 one 签名的方法,但是返回类型不同!编译器不会接受它,但是可以通过直接操作编码来做到这一点.

That also gives ability to have two methods with one signature, but different return types! Compiler would not accept it, but it is possible to do it via direct opcoding.

我的问题是为什么? 他们为什么这样做?

My questions is why? Why they did it?

我只有一个主意:防止在运行时进行复杂的类型检查. 您需要查找层次结构,并检查是否存在具有List接口的父级. 这需要时间,只有编译器有时间. JVM没有.

I have only one idea: to prevent sophisticated type checking in the runtime. You need to look up to the hierarchy and check if there is a parent with List interface. It takes time, and only compiler has it. JVM does not.

我说得对吗?

谢谢.

推荐答案

一个原因可能是因为方法重载(而不是覆盖)是在编译时确定的.请考虑以下方法:

One reason may be because method overloading (as opposed to overriding) is determined at compile time. Consider the following methods:

public void doSomething(List util) {}

public void doSomething(ArrayList util) {}

并考虑代码:

doSomething(getList());

如果Java允许更改返回类型并且没有引发异常,则在重新编译之前,调用的方法仍将是doSomething(List)-然后将是doSomething(ArrayList).这意味着工作代码将仅通过重新编译就可以改变行为.

If Java allowed the return type to change and did not throw an exception, the method called would still be doSomething(List) until you recompiled - then it would be doSomething(ArrayList). Which would mean that working code would change behavior just for having recompiled it.

这篇关于Java:为什么.class文件中的方法类型包含返回类型,而不仅是签名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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