- android - 多次调用 OnPrimaryClipChangedListener
- android - 无法更新 RecyclerView 中的 TextView 字段
- android.database.CursorIndexOutOfBoundsException : Index 0 requested, 光标大小为 0
- android - 使用 AppCompat 时,我们是否需要明确指定其 UI 组件(Spinner、EditText)颜色
让我们考虑一下简单的界面:
interface Simple{
void doSth();
}
还有两个实现它的类:
class A implements Simple{
void someOtherMethod(){ .... }
void doSth(){ ... }
private void doSth(int x){ ... }
}
class B implements Simple{
void methodA(){ ..}
// many other methods
void doSth(){ ... }
private void doSth(Object o, long y){ ... }
}
现在,我可以轻松地写:
Simple s = new A();
s.doSth();
Java 的多态性性质将完成剩下的工作。有谁知道如何例如热点,确保链接器将链接到正确的方法,考虑到实现类中可以定义更多的方法,甚至它们的返回类型可以是原始类的子类? Java 是否确保接口(interface)方法始终从 vtable 中的某个偏移量开始,例如0?
最佳答案
在我们研究这个之前,让我们简化一下这个例子:
interface Foo {
void bar();
}
class AFoo implements Foo {
int i;
@Override
public void bar() {
i++;
}
}
class AnotherFoo implements Foo {
int i;
@Override
public void bar() {
i--;
}
}
public class Test {
public static void main(String[] args) {
Foo foo = new AFoo();
foo.bar();
}
}
编译后,我们使用
javap.exe -verbose Test.class
检查生成的字节代码:
public static void main(java.lang.String[]);
flags: ACC_PUBLIC, ACC_STATIC
Code:
stack=2, locals=2, args_size=1
0: new #16 // class tools/AFoo
3: dup
4: invokespecial #18 // Method tools/AFoo."<init>":()V
7: astore_1
8: aload_1
9: invokeinterface #19, 1 // InterfaceMethod tools/Foo.bar:()V
14: return
在类加载时,代码会被链接起来,即 specified Java 语言规范如下:
The binary representation of a class or interface references other classes and interfaces and their fields, methods, and constructors symbolically, using the binary names (§13.1) of the other classes and interfaces (§13.1). For fields and methods, these symbolic references include the name of the class or interface type of which the field or method is a member, as well as the name of the field or method itself, together with appropriate type information.
Before a symbolic reference can be used it must undergo resolution, wherein a symbolic reference is checked to be correct and, typically, replaced with a direct reference that can be more efficiently processed if the reference is used repeatedly.
请注意,这个“直接引用”是指方法的声明。如果有多个实现,运行时此时无法知道将使用哪个方法。也就是说,多态性不是在 Java 语言规范所谓的链接期间解决的,而是在执行实际方法调用表达式时解决的。这是specified根据 Java 虚拟机规范:
Let C be the class of objectref. The actual method to be invoked is selected by the following lookup procedure:
If C contains a declaration for an instance method with the same name and descriptor as the resolved method, then this is the method to be invoked, and the lookup procedure terminates.
Otherwise, if C has a superclass, this same lookup procedure is performed recursively using the direct superclass of C; the method to be invoked is the result of the recursive invocation of this lookup procedure.
Otherwise, an AbstractMethodError is raised.
如何实际实现这一点取决于 JVM 的实现。对于 Oracle Hotspot JVM,文档包含 rather detailed explanation :
When an invokeinterface call is linked, the linker resolves the call to an abstract target method, in an interface. This boils down to a target interface and a so-called itable index within that interface.
Target interfaces are never statically guaranteed by the JVM verifier; every invokeinterface receiver is typed as a simple object reference. Therefore (unlike invokevirtual calls), no assumptions can be made about the receiver's vtable layout. Instead, the receiver's class (as represented by its _klass field) must be checked more carefully. Where a virtual call can blindly perform two or three indirections to reach the target method, an interface call must first inspect the receiver's class to determine (a) if that class actually implements the interface, and (b) if so, where that interface's methods are recorded within that particular class.
There is no simple prefixing scheme in which an interface's methods are displayed at fixed offsets within every class that implements that interface. Instead, in the general (non-monomorphic) case, an assembly-coded stub routine must fetch a list of implemented interfaces from the receiver's InstanceKlass, and walk that list seeking the current target interface.
Once that interface is found (within the receiver's InstanceKlass), things get a little easier, because the interface's methods are arranged in an itable, or "interface method table", a display of methods whose slot structure is the same for every class that implements the interface in question. Therefore, once the interface is found within the receiver's InstanceKlass, an associated offset directs the assembly stub to an itable embedded in the InstanceKlass (just after the vtable, as one might expect). At that point, invocation proceeds as with virtual method calls.
Nearly the same optimizations apply to interface calls as to virtual calls. As with virtual calls, most interface calls are monomorphic, and can therefore be rendered as direct calls with a cheap check.
Here is a generic instruction trace of a polymorphic interface call:
callSite:
set #calledInterface, CHECK
call #itableStub[itableSlot]
---
itableStub[itableSlot]:
load (RCVR + #klass), KLASS_TEM
load (KLASS_TEM + #vtableSize), TEM
add (KLASS_TEM + TEM), SCAN_TEM
tryAgain:
# this part is repeated zero or more times, usually zero
load (SCAN_TEM + #itableEntry.interface), TEM
cmp TEM, CHECK
jump,eq foundInterface
test TEM
jump,z noSuchInterface
inc #sizeof(itableEntry), SCAN_TEM
jump tryAgain
tryAgain:
load (SCAN_TEM + #itableEntry.interface), TEM
cmp TEM, CHECK
jump,eq foundInterface
foundInterface:
load (SCAN_TEM + #itableEntry.offset), TEM
load (KLASS_TEM + TEM + #itableSlot), METHOD
load (METHOD + #compiledEntry), TEM
jump TEM
---
compiledEntry:
...
In all, that is six memory references and two nonlocal jumps.
迂腐的注释:以上所有内容都适用于调用接口(interface)方法。调用类中声明的抽象方法使用 different bytecode instruction ,还有一个稍微简单一点的 implementation in the Oracle Hotspot JVM .
关于Java-继承实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22331796/
我正在编写一个具有以下签名的 Java 方法。 void Logger(Method method, Object[] args); 如果一个方法(例如 ABC() )调用此方法 Logger,它应该
我是 Java 新手。 我的问题是我的 Java 程序找不到我试图用作的图像文件一个 JButton。 (目前这段代码什么也没做,因为我只是得到了想要的外观第一的)。这是我的主课 代码: packag
好的,今天我在接受采访,我已经编写 Java 代码多年了。采访中说“Java 垃圾收集是一个棘手的问题,我有几个 friend 一直在努力弄清楚。你在这方面做得怎么样?”。她是想骗我吗?还是我的一生都
我的 friend 给了我一个谜语让我解开。它是这样的: There are 100 people. Each one of them, in his turn, does the following
如果我将使用 Java 5 代码的应用程序编译成字节码,生成的 .class 文件是否能够在 Java 1.4 下运行? 如果后者可以工作并且我正在尝试在我的 Java 1.4 应用程序中使用 Jav
有关于why Java doesn't support unsigned types的问题以及一些关于处理无符号类型的问题。我做了一些搜索,似乎 Scala 也不支持无符号数据类型。限制是Java和S
我只是想知道在一个 java 版本中生成的字节码是否可以在其他 java 版本上运行 最佳答案 通常,字节码无需修改即可在 较新 版本的 Java 上运行。它不会在旧版本上运行,除非您使用特殊参数 (
我有一个关于在命令提示符下执行 java 程序的基本问题。 在某些机器上我们需要指定 -cp 。 (类路径)同时执行java程序 (test为java文件名与.class文件存在于同一目录下) jav
我已经阅读 StackOverflow 有一段时间了,现在我才鼓起勇气提出问题。我今年 20 岁,目前在我的家乡(罗马尼亚克卢日-纳波卡)就读 IT 大学。足以介绍:D。 基本上,我有一家提供簿记应用
我有 public JSONObject parseXML(String xml) { JSONObject jsonObject = XML.toJSONObject(xml); r
我已经在 Java 中实现了带有动态类型的简单解释语言。不幸的是我遇到了以下问题。测试时如下代码: def main() { def ks = Map[[1, 2]].keySet()
一直提示输入 1 到 10 的数字 - 结果应将 st、rd、th 和 nd 添加到数字中。编写一个程序,提示用户输入 1 到 10 之间的任意整数,然后以序数形式显示该整数并附加后缀。 public
我有这个 DownloadFile.java 并按预期下载该文件: import java.io.*; import java.net.URL; public class DownloadFile {
我想在 GUI 上添加延迟。我放置了 2 个 for 循环,然后重新绘制了一个标签,但这 2 个 for 循环一个接一个地执行,并且标签被重新绘制到最后一个。 我能做什么? for(int i=0;
我正在对对象 Student 的列表项进行一些测试,但是我更喜欢在 java 类对象中创建硬编码列表,然后从那里提取数据,而不是连接到数据库并在结果集中选择记录。然而,自从我这样做以来已经很长时间了,
我知道对象创建分为三个部分: 声明 实例化 初始化 classA{} classB extends classA{} classA obj = new classB(1,1); 实例化 它必须使用
我有兴趣使用 GPRS 构建车辆跟踪系统。但是,我有一些问题要问以前做过此操作的人: GPRS 是最好的技术吗?人们意识到任何问题吗? 我计划使用 Java/Java EE - 有更好的技术吗? 如果
我可以通过递归方法反转数组,例如:数组={1,2,3,4,5} 数组结果={5,4,3,2,1}但我的结果是相同的数组,我不知道为什么,请帮助我。 public class Recursion { p
有这样的标准方式吗? 包括 Java源代码-测试代码- Ant 或 Maven联合单元持续集成(可能是巡航控制)ClearCase 版本控制工具部署到应用服务器 最后我希望有一个自动构建和集成环境。
我什至不知道这是否可能,我非常怀疑它是否可能,但如果可以,您能告诉我怎么做吗?我只是想知道如何从打印机打印一些文本。 有什么想法吗? 最佳答案 这里有更简单的事情。 import javax.swin
我是一名优秀的程序员,十分优秀!