原文地址:https://blog.csdn.net/a724888/article/details/78404643
下面我们看看一段 C 代码:
#include<stdio.h> void sayHello(int age) { int x = 32; int y = 2323; age = x + y; } void main() { int age = 22; sayHello(age); }很简单的一段代码,我们汇编生成相应的汇编代码,省略了部分链接代码,留下的是核心的部分:
main: pushl %ebp movl %esp, %ebp subl $20, %esp movl $22, -4(%ebp) movl -4(%ebp), %eax movl %eax, (%esp) call sayHello leave ret sayHello: pushl %ebp movl %esp, %ebp subl $16, %esp movl $32, -4(%ebp) movl $2323, -8(%ebp) movl -8(%ebp), %eax movl -4(%ebp), %edx addl %edx, %eax movl %eax, -12(%ebp) leave retleave 指令等效于以下两条指令之和:
movl %ebp %esp popl %ebp局部变量表不同于操作数栈,它采用索引机制访问元素,而不同于操作数栈的出入栈方式。例如:
public void sayHello(String name){ int x = 23; int y = 43; x++; x = y - 2; long z = 234; x = (int)z; String str = new String("hello wrold "); }那么哪些方法是被静态解析了,哪些方法需要动态解析呢?
比如下面这段代码:
Object obj = new String("hello"); obj.equals("world");首先我们看一段代码:
public class Father { } public class Son extends Father { } public class Daughter extends Father { } public class Hello { public void sayHello(Father father){ System.out.println("hello , i am the father"); } public void sayHello(Daughter daughter){ System.out.println("hello i am the daughter"); } public void sayHello(Son son){ System.out.println("hello i am the son"); } } public static void main(String[] args){ Father son = new Son(); Father daughter = new Daughter(); Hello hello = new Hello(); hello.sayHello(son); hello.sayHello(daughter); }JDK1.7 提供了两种方式来支持 Java 的动态特性,invokedynamic 指令和 java.lang.invoke 包。这两者的实现方式是类似的,我们只介绍后者的基本内容。
//该方法是我自定义的,并非 invoke 包中的 public static MethodHandle getSubStringMethod(Object obj) throws NoSuchMethodException, IllegalAccessException { //定义了一个方法模板,规定了待搜索的方法的返回值和参数类型 MethodType methodType = MethodType.methodType(String[].class,String.class); //查找符合指定方法简单名称和模板信息的方法 return lookup().findVirtual(obj.getClass(),"split",methodType).bindTo(obj); } public static void main(String[] args){ Object obj = new String("hello-world"); //定位方法,并传入参数执行方法 String[] strs = (String[]) getSubStringMethod(obj).invokeExact("-"); System.out.println(strs[0]); }原文地址:https://blog.csdn.net/a724888/article/details/78396462
假设有:
public static int value = 123;一种特殊情况是,如果字段属性表中包含ConstantValue属性,那么准备阶段变量value就会被初始化为ConstantValue属性所指定的值,比如上面的value如果这样定义:
public static final int value = 123;