🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
## Java调用方法的参数传递 1. 如果形参是[基础数据类型](Java%E5%9F%BA%E7%A1%80%E6%95%B0%E6%8D%AE%E7%B1%BB%E5%9E%8B.md),实参向形参传递时,就是值传递。在调用方法栈帧内申请变量,存的是实参的值。 2. 如果形参是对象数据类型,实参向形参传递是,则是将形参内存的堆内对象的引用地址复制给形参。实际上还是值传递,只是值指的是对象的引用地址。 ## 原理 ***Java在方法传递参数时,是将变量复制一份,然后传入方法体内执行。*** ## 例子 ### int类型是值传递 ~~~ System.out.println("--------int start----------"); // int为基本类型,是值传递,value还是等于100 int value = 100; System.out.println("value address:"+VM.current().addressOf(value)); changeNum(value); System.out.println("value:"+value); System.out.println("value address:"+VM.current().addressOf(value)); System.out.println("--------int end----------"); ~~~ ~~~ private static void changeNum(int a){ System.out.println("method value address before:"+VM.current().addressOf(a)); a = 100; System.out.println("method value address after:"+VM.current().addressOf(a)); } ~~~ 输出: ``` --------int start---------- value address:32570546328 method value address before:32570546328 method value address after:32570544744 value:100 value address:32570546328 --------int end---------- ``` ### 对象类型是引用传递 ~~~ System.out.println("--------A.class start----------"); A a = new A(12,"123"); System.out.println("A.class address:"+VM.current().addressOf(a)); changeA(a); System.out.println("A.class value:"+a); System.out.println("A.class address:"+VM.current().addressOf(a)); System.out.println("--------A.class end----------"); ~~~ ~~~ static class A{ public int age; public String name; public A(int age, String name) { this.age = age; this.name = name; } @Override public String toString() { return "A{" + "age=" + age + ", name='" + name + '\'' + '}'; } } ~~~ ~~~ private static void changeA(A a){ System.out.println("method A.class address before:"+VM.current().addressOf(a)); a.age = 1; a.name = "xxx"; System.out.println("method A.class address after:"+VM.current().addressOf(a)); } ~~~ 输出: ``` --------A.class start---------- A.class address:32586262016 method A.class address before:32586262016 method A.class address after:32586262016 A.class value:A{age=1, name='xxx'} A.class address:32586262016 --------A.class end---------- ```