编程语言的实现可能会有所不同。下面是一些代码示例:
C语言中,跳转表通常被编译到一个代码段中。可以使用objdump命令来查看ELF文件中的跳转表位置。
#include
void func1() {
printf("function 1\n");
}
void func2() {
printf("function 2\n");
}
int main() {
void (*jump_table[])() = { func1, func2 };
int choice = 1;
jump_table[choice]();
return 0;
}
Java中,跳转表(又称为虚方法表)是在类的元数据中保存的。可以使用javap命令来查看Java字节码中的虚方法表。
public abstract class Animal {
public abstract void eat();
}
public class Dog extends Animal {
@Override
public void eat() {
System.out.println("Dog is eating.");
}
}
public class Main {
public static void main(String[] args) {
Animal animal = new Dog();
animal.eat();
}
}
Python中,跳转表是在类对象的__dict__属性中保存的。可以使用dir函数来查看类对象的属性和方法列表。
class Animal:
def eat(self):
pass
class Dog(Animal):
def eat(self):
print("Dog is eating.")
animal = Dog()
animal.eat()