-
java中的基本数据类型传递属于引用传递,并不会像c/c++实现指针传递;
-
通过包装类对象配合反射可以实现数据的交换。
java里面无法通过方法来达到交换实际参数的值的,你的方法里面交换的只是形式参数,而真正实际参数的值是无法交换的。而且不管参数是基本类型还是引用类型,java都不能通过方法来做到这点。
因为JAVA中都是传值的,所以实现交换就不能靠类似于C++指针或者引用的东西,虽然JAVA中也有引用,但是这里的引用已经退化了。不是真正意义的引用了。
1、非类成员 包装类对象
public classTest{
public static void main(String[] args) throws Exception{
Integer a = 1;
Integer b = 2;
System.out.println("before : a=="+a+";b=="+b);
swap(a,b);
System.out.println("after : a=="+a+";b=="+b);
}
public static void swap(Integer num1,Integer num2) throws IllegalAccessException,NoSuchFieldException{
Field field = num1.getClass().getDeclaredField("value");
field.setAccessible(true);
int temp = num1;
field.set(num1,num2);
field.set(num2,new Integer(temp));
}
}
2、类成员 包装类对象
java 反射 getDeclaredField 获取私有保护字段, 再setAccessible(true)取消对权限的检查 实现对私有的访问和赋值。
package test;
import java.lang.reflect.Field;
public class Test {
//将属性声明为包装类型
private Character from;
private Character pass;
private Character to;
public static void main(String[] args) {
Test test = new Test('A', 'B', 'C');
test.swap(test.from, test.to);
System.out.println(test.toString());
}
Test(Character from, Character pass, Character to) {
this.from = from;
this.pass = pass;
this.to = to;
}
// 交换
private void swap(Character num1, Character num2) {
try {
Field field = num1.getClass().getDeclaredField("value");
field.setAccessible(true);
try {
char temp = num1;
field.set(num1, num2);
field.set(num2, new Character(temp));
} catch (IllegalArgumentException | IllegalAccessException e) {
e.printStackTrace();
}
} catch (NoSuchFieldException | SecurityException e) {
e.printStackTrace();
}
}
@Override
public String toString() {
return "Test [from=" + from + ", pass=" + pass + ", to=" + to + "]";
}
}