I found a knowledge point about creating objects in Java, and I was scared to write it down quickly

We know that Java is object-oriented programming. What is a rhetoric? Everything is an object!

You want to view the properties (non-static), how to check? Want an object!

You want to call a method (non-static), how do you call it? Want an object!

No object, it's terrible! o(╥﹏╥)o, I can’t do anything~~

So, if we have no object, we will make a new one! If there is no object, we create an object!

This is the creation of the object. Let’s talk about it today. If you have such an "object", there is no need for an object. Take a look at this!

1. Use the keyword new

When you create a Class class, you actually create a constructor with no parameters by default. Of course, you can also overload a construction method according to your needs, so the default no-parameter construction method is naturally invalid. At this time, if you want to call a no-parameter construction method, you can only write another no-parameter construction method by hand. Look at the previous code (*^▽^*).

public class BeautifulGirl {

    private Integer age;

    private String height;

    private String name;

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public String getHeight() {
        return height;
    }

    public void setHeight(String height) {
        this.height = height;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

Let's call

 public static void main(String[] args) throws Exception {
        BeautifulGirl beautifulGirl = new BeautifulGirl();
        beautifulGirl.setAge(20);
        beautifulGirl.setHeight("175cm");
        System.out.println(JSON.toJSONString(beautifulGirl));
    }

//输出
//{"age":20,"height":"175cm"}

This is of course no problem for me. This is also the most commonly used way to get objects. However, some object parameters cannot be empty. For example, this BeautifulGirl must have a name, so the construction method is overloaded.

   public BeautifulGirl(String name) {
        this.name = name;
    }

At this time, if you are new again, you have to write the parameters, otherwise it will prompt BeautifulGirl(String) in BeautifulGirl cannot be applied to (), so generally when overloading the construction method, the no-parameter construction method will also be written to prevent I want a new object somewhere, but new doesn't come out, hahaha.

2. Use reflection

Still this BeautifulGirl, we do not use new, and use the reflection of java to construct this object.

public static void main(String[] args) throws Exception {
        Class<?> bClass = Class.forName("com.pindao.ehr.center.operateVO.BeautifulGirl");
        Object o = bClass.newInstance();
        if (o instanceof BeautifulGirl) {
            BeautifulGirl beautifulGirl = (BeautifulGirl) o;
            beautifulGirl.setAge(20);
            System.out.println("beautifulGirl:"+JSON.toJSONString(beautifulGirl));
        }
    }

Eh? Report an error? Will this kind of basic reflection still have problems? Post to see

Exception in thread "main" java.lang.InstantiationException: com.pindao.ehr.center.operateVO.BeautifulGirl
	at java.lang.Class.newInstance(Class.java:427)
	at com.pindao.ehr.center.operateVO.TempTest.main(TempTest.java:9)
Caused by: java.lang.NoSuchMethodException: com.pindao.ehr.center.operateVO.BeautifulGirl.<init>()
......

As you can see, the place where the error is reported is newInstance, and the prompt is NoSuchMethodException, there is no such method exception! Oh, it turns out that there is no method to instantiate this class. Isn't instantiation just calling the constructor? Take a closer look, hey, the construction method is overloaded by me, it is not parameterless, newInstance clearly only needs a parameterless construction method! I was so scared that I quickly added the parameterless construction method.

Let's run it again, so the 20-year-old beautiful girl is out!

{"age":20}

Process finished with exit code 0

Of course, it is also possible to use reflection to change the wording

         ClassLoader loader = ClassLoader.getSystemClassLoader();
                  Class<?> aClass = 
                  loader.loadClass("com.pindao.ehr.center.operateVO.BeautifulGirl");
        Object o = aClass.newInstance();
        if (o instanceof BeautifulGirl) {
            BeautifulGirl beautifulGirl = (BeautifulGirl) o;
        }
        
        //--------------------------------------------------------

        BeautifulGirl t = new BeautifulGirl();
        
        Class<? extends BeautifulGirl> aClass1 = t.getClass();
        BeautifulGirl beautifulGirl = aClass1.newInstance();

3. Clone() and serialization

The clone() method may be a bit strange to everyone, but everyone is familiar with the Object class, right? Object is the parent class of all classes, and Object has some of its own methods, including equals, wait, notify, toString, and so on. Since the object inherits Object, it is natural to rewrite the Clone method and create a new object, but this also needs to be called by the object. Also need to rewrite the method, this should not be used much.

There is also serialization. In this case, you need to implement the serialization interface Serializable. Some RPC calls and parameter reception are all serialized and deserialized. I won’t say more about this here. There are too many things. If If you are interested, you can take a look at serialization and deserialization.

4. Use Unsafe

Whether it is new or reflection, or Clone, even some serialization methods must use the parameter-free construction method of the object. If there is no parameter-free construction method, then this BeautifulGirl object will naturally be out of existence, so I am now What if I want a BeautifulGirl object?

Don't worry, there are tricks!

Object BeautifulGirl can't run!

We also have the Unsafe toolkit! We use reflection to find the BeautifulGirl object directly!

Since the construction of examples of these methods has been encapsulated in Gson, I will not rewrite it. Let's see the effect!

 public static void main(String[] args) throws Exception {

        Map<Type, InstanceCreator<?>> instanceCreators = new HashMap<>();
        ConstructorConstructor constructorConstructor = new ConstructorConstructor(instanceCreators);

        ObjectConstructor<BeautifulGirl> constructor = constructorConstructor.get(TypeToken.get(BeautifulGirl.class));
        BeautifulGirl beautifulGirl = constructor.construct();
        beautifulGirl.setName("jingjing");
        beautifulGirl.setAge(20);
        beautifulGirl.setHeight("175cm");
        System.out.println(JSON.toJSONString(beautifulGirl));
    }

Execution result (no parameter structure has been covered):

{"age":20,"height":"175cm","name":"jingjing"}

Process finished with exit code 0

Well, if you are interested, you can go to see the source code of Gson. That's it for today, continue to go back and see Unsafe! o(* ̄︶ ̄*)o

No sacrifice,no vectory!

Guess you like

Origin blog.csdn.net/zsah2011/article/details/112557331