Goodbye, single dog! There are six ways for Java to create objects. You don't have to lick the dog anymore..

Posted by codebuilder on Mon, 14 Feb 2022 04:54:57 +0100

background

It's the annual Valentine's day again. I wish all programmers have lovers and get married!

Today, the official account was advertised and temporarily pigeon. This Valentine's Day is a little hurt. Fortunately, there is no pigeon..

What should I write on Valentine's day?!

You must have a lot of single dog s, right?

It doesn't matter. Stack leader, this article teaches you six ways to create objects, from low-end to high-end. There is always one suitable for you. If there is no object, generate one by yourself!

2022, be sure to take off the bill. Bye, single dog!

6 ways to create objects

Suppose there is a girlfriend class:

@Data
@NoArgsConstructor
@AllArgsConstructor
class GirlFriend {

    private String name;

}

The annotation uses Lombok framework annotation, which is convenient for rapid development. If you are not familiar with this article:

Recommend a code artifact to save at least half of the code!

Method 1: new an object

If there is no object, just new. Yes, use the new keyword, which is also the simplest and direct way for Java to create objects.

Example code:

/**
 * new An object
 * @author: Stack length
 * @from: Official account Java technology stack
 */
@Test
public void girlFriend1() {
    GirlFriend girlFriend = new GirlFriend("new An object");
    System.out.println(girlFriend);
}

Output result:

GirlFriend(name=new an object)

Method 2: clone an object

A friend has a girlfriend, but you don't. If you can, clone someone else's girlfriend?

Let the girlfriend class first implement the clonable interface and its clone() method:

/**
 * Girlfriend class
 * @author: Stack length
 * @from: Official account Java technology stack
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
class GirlFriend implements Cloneable {

    private String name;

    @Override
    protected Object clone() throws CloneNotSupportedException {
        return super.clone();
    }
    
}

Note: shallow copy is used by default in this demonstration, that is, only basic type fields are cloned. For reference types, the clone() method needs to be rewritten to manually assign the value of the reference field.

Now clone an object, sample code:

@Test
public void girlFriend2() throws CloneNotSupportedException {
    GirlFriend girlFriend1 = new GirlFriend("Clone an object");
    GirlFriend girlFriend2 = (GirlFriend) girlFriend1.clone();
    System.out.println(girlFriend2);
}

Output result:

GirlFriend(name = clone an object)

The advantage of using cloning is that you can quickly create an object with the same value as the original object. The field value of the object is the same, but there are two different references.

Method 3: the class dispatches an object

Send one directly to your girlfriend:

/**
 * Class to dispatch an object
 * @author: Stack length
 * @from: Official account Java technology stack
 */
@Test
public void girlFriend3() throws InstantiationException, IllegalAccessException {
    GirlFriend girlFriend = GirlFriend.class.newInstance();
    girlFriend.setName("Class to dispatch an object");
    System.out.println(girlFriend);
}

Output result:

GirlFriend(name = class sends an object)

In addition, the latest and most complete Java interview questions have been sorted out, and wechat search java interview library applet swipes questions online.

Method 4: reflect an object

If you know where the girlfriend class is (the full path of the class), but it is not loaded, reflect an object:

/**
 * Reflect an object
 * @author: Stack length
 * @from: Official account Java technology stack
 */
@Test
public void girlFriend4() throws InstantiationException, IllegalAccessException, ClassNotFoundException {
    GirlFriend girlFriend = (GirlFriend) Class.forName("cn.javastack.test.jdk.core.GirlFriend").newInstance();
    girlFriend.setName("Reflect an object");
    System.out.println(girlFriend);
}

Output result:

Girl name = friend object

Method 5: construct an object

Knowing the construction of girlfriend class, you can call the constructor to construct an object:

/**
 * Construct an object
 * @author: Stack length
 * @from: Official account Java technology stack
 */
@Test
public void girlFriend5() throws NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
    GirlFriend girlFriend = GirlFriend.class.getConstructor().newInstance();
    girlFriend.setName("Construct an object");
    System.out.println(girlFriend);
}

Output result:

GirlFriend(name = construct an object)

Here, you can also combine reflection to construct an object at the same time.

Method 6: deserialize an object

This is similar to the function of cloning. If a girlfriend was serialized (saved) on disk, it can be deserialized now.

Java serialization base is not introduced, and long before the stack length, I have finished sorting it out, and can read in the official account Java technology stack menu.

First, make your girlfriend Serializable and implement the Serializable interface:

/**
 * Girlfriend class
 * @author: Stack length
 * @from: Official account Java technology stack
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
class GirlFriend implements Cloneable, Serializable {

    private static final long serialVersionUID = 1L;
    
    private String name;

    @Override
    protected Object clone() throws CloneNotSupportedException {
        return super.clone();
    }

}

Serialization / deserialization object example code:

/**
 * Deserialize an object
 * @author: Stack length
 * @from: Official account Java technology stack
 */
@Test
public void girlFriend6() throws IOException, ClassNotFoundException {
    GirlFriend girlFriend1 = new GirlFriend("Deserialize an object");

    // I have a girlfriend
    ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream("gf.obj"));
    objectOutputStream.writeObject(girlFriend1);
    objectOutputStream.close();

    // Deserialize
    ObjectInputStream objectInputStream = new ObjectInputStream(new FileInputStream("gf.obj"));
    GirlFriend girlFriend2 = (GirlFriend) objectInputStream.readObject();
    objectInputStream.close();

    System.out.println(girlFriend2);
}

Output result:

GirlFriend(name = deserialize an object)

summary

The complete sample code of this article has been uploaded to Github:

https://github.com/javastacks...

Welcome to Star learning, the follow-up will continue to update ~

If you don't like using code to generate objects for yourself, you can also try this Java confession poem:

Wrote a Java confession poem, girlfriend don't worry!

I wish you success, but the other party is limited to programmers, otherwise you will not understand.

What other ways do you know to create objects? Welcome to leave a message to discuss ~!

Well, today's sharing is here. The stack will share more interesting Java technology and latest technology information. We will pay attention to the Java push for the official account. I will also organize the main Java interview questions and reference answers. I will reply to the key words in the official account.

Finally, I feel that if my article is useful to you, use your small hand to read and forward it. It's not easy to be original. The stack leader needs your encouragement.

Copyright notice: This article is the official account of the "Java technology stack". It is reproduced and quoted. Please note the source of this article. All plagiarism and manuscripts must be complains of infringement, and the consequences will be conceited, and the right to pursue its legal liability should be retained.

Recent hot article recommendations:

1.1000 + Java interview questions and answers (2022 latest version)

2.Hot! The Java collaboration is coming...

3.Spring Boot 2.x tutorial, too complete!

4.20w programmer red envelope cover, get it quickly...

5.Java development manual (Songshan version) is the latest release. Download it quickly!

Feel good, don't forget to like + forward!

Topics: Java