剛學習Java不久,今天遇到一個問題,需要在方法中修改傳入的對象的值,確切的說是需要使用一個方法,創建一個對象,並把其引用返回,熟悉C#的我
的第一反應就是C#中的ref/out關鍵字,結果發現Java中沒有類似的關鍵字,所以只能想想如何解決此問題.
參數傳遞:
方法的參數傳遞有兩種,一種是值傳遞,一種是引用傳遞,但是其實都是拷貝傳遞。
值傳遞:就是把傳遞的【數據本身拷貝一份】,傳入方法中對其進行操作,拷貝的是值。
引用傳遞:就是把指向某個對象的【引用拷貝一份】,傳入方法中通過此引用可以對對象進行操作。
那么就我當前的問題而言,我需要一個方法,我傳入一個引用,在方法中創建所需對象.
那么在Java中就會只能給當前對象在封裝一層(定義一個新類),使得需要創建的對象成為新類的成員,在方法中為成員賦值
Example:
C#:
/// <summary>
/// model
/// </summary>
public class Student
{
public string Name;
public int Age;
}
/// 方法:
/// <summary>
/// 錯誤示范
///
/// student這個引用是拷貝傳入的,創建新的對應Student
/// 把引用賦給student,當方法退棧之后student引用回到壓棧前
/// 則Student對象引用數為0,等待GC,引用student依舊是原來的值(邏輯地址)
/// </summary>
/// <param name="student"></param>
static void createStudent(Student student)
{
student = new Student { Name ="Stephen Lee", Age = 1};
}
/// <summary>
/// 正確做法
///
/// 通過ref關鍵字,把操作權讓給方法內部
/// </summary>
/// <param name="student"></param>
static void createStudent(ref Student student)
{
student = new Student { Name = "Stephen Lee", Age = 1 };
}
// Client
static void Main(string[] args)
{
Console.WriteLine("錯誤示范");
Student student1 = null;
createStudent(student1);
if (student1 == null)
Console.WriteLine("創建對象失敗");
else
Console.WriteLine("創建對象成功,Name:" + student1.Name);
Console.WriteLine("正確做法");
Student student2 = null;
createStudent(ref student2);
if (student2 == null)
Console.WriteLine("創建對象失敗");
else
Console.WriteLine("創建對象成功,Name:" + student2.Name);
}
Java:
/** Model
* @author Stephen
*
*/
public class Student
{
public String Name;
public int Age;
public Student(String name,int age)
{
this.Name = name;
this.Age = age;
}
}
/** 錯誤示范,原因同C#
* @param student
*/
private void createStudent(Student student)
{
student = new Student("Stephen Lee",1);
}
/** 正確做法
* @param studentPack
*/
private void createStudent(StudentPack studentPack)
{
studentPack.student = new Student("Stephen Lee",1);
}
/** 包裝器
* @author Stephen
*
*/
public class StudentPack
{
public Student student;
}
// Client
StudentPack studentPack = new StudentPack();
createStudent(studentPack);
System.out.println(studentPack.student.Name);
ref/out關鍵字:http://msdn.microsoft.com/zh-cn/library/14akc2c7.aspx