When crafting objects in Java, using the constructor is a go-to approach. However, there are additional avenues to consider.
Java offers four primary ways to instantiate objects:
new Keyword: This familiar method is widely employed and involves explicitly calling a class's constructor.
MyObject object = new MyObject();
Class.forName(): This approach comes in handy when you know the class name and it has a public default constructor.
MyObject object = (MyObject) Class.forName("subin.rnd.MyObject").newInstance();
clone(): If you have an existing object, you can duplicate it using the clone() method.
MyObject anotherObject = new MyObject(); MyObject object = (MyObject) anotherObject.clone();
Object Deserialization: This process involves creating an object from its serialized form.
ObjectInputStream inStream = new ObjectInputStream(anInputStream ); MyObject object = (MyObject) inStream.readObject();
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3