In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article focuses on "how to use new to create objects", interested friends may wish to take a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn how to use new to create objects.
Use new to create objects
Using new to create an object is the easiest way. New is a keyword in Java. New instantiates a class by allocating memory to a new object and returning a reference to that memory. Instantiating a class is tantamount to creating an object, because the class is also an object; new is also responsible for calling the object's constructor. Here is the code that uses new to create the object.
Object obj = new Object ()
In this code, we allocate a piece of memory in the heap area, and then point the obj object to this memory area.
I wonder if you have seen the bytecode of new? Here is the bytecode of this code
In Java, we think that to create an object is to call its constructor, so the object we construct using new Object () is actually calling the parameterless constructor of the Object class. However, through the bytecode, we find that the creation of the object and the invocation of its constructor are separate.
The new of bytecode means that an object is created in the heap and a reference to the object is pushed onto the stack. Invokespecial indicates that the constructor that calls the object has no parameters. In fact, JVM provides five method call instructions, which are
Invokestatic: this directive is used to call static methods, that is, methods modified with the static keyword
Invokespecial: this directive is used in three scenarios: calling instance constructors, calling private methods (methods modified by the private keyword), and parent methods (methods called by the super keyword)
Invokeinterface: this instruction is used to call the interface method and determine another object that implements this interface at run time
Invokevirtual: this instruction is used to call virtual methods (that is, methods other than the above three cases)
Invokedynamic: called after the method referenced by the call point qualifier is dynamically parsed at run time; proposed in JDK 1.7.It is mainly used to support dynamic scripting languages on JVM (such as Groovy,Jython, etc.)
Well, now that you know what new and invokespecial are for, what about the dup instruction?
Dup copies the last element on the stack and then pushes it onto the stack again; so if there is an object reference on the stack and dup is called, there are now two references to that object on the stack. It seems that I don't know why, so when I asked for help online, I found the R big explanation.
Source: https://www.zhihu.com/question/52749416
The later astore consumes the reference at the top of the Operand stack and saves it to the specified local variable.
If you use new Object () directly without creating a local variable, pay attention to its bytecode.
Do you see the slight difference? The astore_1 in the figure above turns out to be pop, which means that new Object () does not hold the local variable of the object, but consumes it directly. Well, as expected.
So this is the first way to create it, that is, using new.
Use the newInstance method to create
This newInstance method refers to the method in the class class, and the newInstance method calls the no-parameter constructor to create the object.
We can use the newInstance method to create an object. Here is the sample code
User user = (User) Class.forName ("com.cxuan.test.User") .newInstance (); / / or use User user = User.class.newInstance ()
Let's analyze this bytecode. In fact, using the first method and the second way is short of a Class.forName bytecode. This is a static method, and we should use invokestatic. Let's verify it.
Bytecode in the first way
Bytecode in the second way
As you can see, what we verified is correct.
So what does this bytecode mean?
Ldc means to push references from the constant pool into the current stack, invokestatic and invokevirtual we explained above, and then checkcast, this bytecode means type conversion, because newInstance generates an Object object, so we need to convert it to the User type we need, which is what this bytecode does.
Use reflection to create objects
Using reflection to create an object actually uses the newInstance method, but this method is the method of the constructor in Constructor, Java reflection, and we can create a new object in this way. As shown in the following code
Constructor constructor = User.class.getConstructor (); User user = constructor.newInstance ()
Here is its bytecode
Iconst_0 is explained here, which means that the int value of 0 is loaded on the stack, which is equivalent to preparing the bytecode for parameter allocation for the getConstructor method.
To verify this conclusion, let's look at the bytecode of other methods from simple optimization.
User.class.getDeclaredField ("id")
Its bytecode is as follows:
As you can see, the second ldc is actually a parameter in getDeclaredField, of type String, so you use ldc, which pushes the reference onto the stack.
Use object cloning to create objects
This is the fourth way to create it, using the clone () method in the Cloneable class, provided that you implement the Cloneable interface and its defined clone method. Creating an object with the clone method does not call any constructors.
As shown in the following code
Constructor constructor = User.class.getConstructor (); User user = constructor.newInstance (); user.setName ("cxuan"); User user2 = (User) user.clone (); System.out.println (user2.getName ())
Output cxuan
Its bytecode is as follows
This bytecode is a bit long, but the concept and meaning of bytecode have been introduced above, the most important thing is to push onto the stack and call the corresponding instance method.
Object cloning is a point that the interviewer likes very much. I will analyze the difference between shallow copy and deep copy later.
Create objects using deserialization
When we use serialization and deserialization, JVM also creates a separate object for us. When deserializing, the JVM creation object does not call any constructor, as shown in the following code
ObjectOutputStream out = new ObjectOutputStream (new FileOutputStream ("xxx")); out.writeObject (user2); out.close (); / / Deserialization ObjectInputStream in = new ObjectInputStream (new FileInputStream ("xxx")); User user3 = (User) in.readObject (); in.close (); user3.setName ("cxuan003"); System.out.println (user3 + ", hashcode:" + user3.hashCode ())
This decompiled bytecode file is relatively long, so I won't post it here. Readers can compile and see for themselves. In fact, there are no special bytecode instructions, most of which we have mentioned above.
At this point, I believe you have a deeper understanding of "how to use new to create objects". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.