你能通过Java引用吗?

dbo*_*nes 5 c# java parameters pass-by-reference

很抱歉,如果这听起来像是一个新手问题,但前几天Java开发人员提到通过引用传递一个参数(通过引用传递一个参考对象)

从C#的角度来看,我可以通过值或引用传递引用类型,这也适用于值类型

我写了一个noddie控制台应用程序来表明我的意思..我可以用Java做到这一点吗?

namespace ByRefByVal
{
    class Program
    {
        static void Main(string[] args)
        {
            //Creating of the object
            Person p1 = new Person();
            p1.Name = "Dave";
            PrintIfObjectIsNull(p1); //should not be null

            //A copy of the Reference is made and sent to the method
            PrintUserNameByValue(p1);
            PrintIfObjectIsNull(p1);

            //the actual reference is passed to the method
            PrintUserNameByRef(ref p1);    //<-- I know im passing the Reference
            PrintIfObjectIsNull(p1);

            Console.ReadLine();
        }

        private static void PrintIfObjectIsNull(Object o)
        {
            if (o == null)
            {
                Console.WriteLine("object is null");
            }
            else
            {
                Console.WriteLine("object still references something");
            }
        }

        /// <summary>
        /// this takes in a Reference type of Person, by value
        /// </summary>
        /// <param name="person"></param>
        private static void PrintUserNameByValue(Person person)
        {
            Console.WriteLine(person.Name);
            person = null; //<- this cannot affect the orginal reference, as it was passed in by value.
        }

        /// <summary>
        /// this takes in a Reference type of Person, by reference
        /// </summary>
        /// <param name="person"></param>
        private static void PrintUserNameByRef(ref Person person)
        {
            Console.WriteLine(person.Name);
            person = null; //this has access to the orginonal reference, allowing us to alter it, either make it point to a different object or to nothing.
        }


    }

    class Person
    {
        public string Name { get; set; }
    }
}
Run Code Online (Sandbox Code Playgroud)

如果java不能这样做,那么它只是按值传递引用类型?(这是公平的说法)

非常感谢

骨头

Cor*_*sky 31

不,Java不能这样做.Java只按值传递.它也通过值传递引用.

  • +1对于"它按值传递引用".这里最准确的事情. (14认同)

Dav*_*und 10

通过引用传递是一个经常被Java开发人员误解的概念,可能是因为他们不能这样做.读这个:

http://javadude.com/articles/passbyvalue.htm