Several common methods for creating objects in java and several methods for creating objects in java

Source: Internet
Author: User

Several common methods for creating objects in java and several methods for creating objects in java

Common methods for creating objects in java:

1. Use the new Keyword to create an object

2. Use the reflection mechanism of java to create an object through java. lang. Class or java. lang. reflect. Constructor.

3. Implement the Cloneable interface, and then override the Object. clone () method to create an Object.

4. Implement the serialiable serialization interface. Create an object through the deserialization and the readObject () method of ObjectInputStream.

5. String str = "abc" is directly created by jvm or created by jvm using the String operator "+" String str1 = "a" + "bc"

 

Create an object class TestBean. java

package test.createObj;import java.io.Serializable;public class TestBean implements Cloneable,Serializable{    /**     *      */    private static final long serialVersionUID = -6896355094290356656L;    private String id;    private String name;        public TestBean(String id, String name) {        this.id = id;        this.name = name;    }    public void setName(String name) {        this.name = name;    }    public String getName() {        return name;    }    public void setId(String id) {        this.id = id;    }    public String getId() {        return id;    }    @Override    protected Object clone() throws CloneNotSupportedException {        return super.clone();    }        @Override    public String toString() {        return super.toString()+"  "+id+"  "+name;    }}

Create test class CreateObjTest. java

Package test. createObj; import java. io. file; import java. io. fileInputStream; import java. io. fileOutputStream; import java. io. IOException; import java. io. objectInputStream; import java. io. objectOutputStream; import java. lang. reflect. constructor; public class CreateObjTest {/*** @ param args */@ SuppressWarnings ("rawtypes") public static void main (String [] args) {// 1. new Keyword creates an object TestBean testbean1 = new T EstBean ("1", "Zhang San haha"); // II. reflection mechanism TestBean testbean2 = null; try {Class <?> Clazz = Class. forName ("test. createObj. testBean "); // java is reported when the class contains constructor parameters without any constructor. lang. instantiationException // you need to add a non-argument constructor to the class // testbean2 = (TestBean) clazz. newInstance (); // or get the constructor of the Class Using Reflection. instantiate the object Class [] paramTypes = {String. class, String. class}; Constructor constor = clazz. getConstructor (paramTypes); testbean2 = (TestBean) constor. newInstance ("2", "Li Si");} catch (Exception e) {e. printSt AckTrace () ;}// 3. clone but the class must implement the Cloneable interface and rewrite the clone method in the class. // jdl1.6 Chinese api is said as follows: // if you call the Object clone method on an instance that does not implement the Cloneable interface, a CloneNotSupportedException exception will be thrown. // By convention, classes implementing this interface should use public methods to override Object. clone (it is protected ). // See Object. clone () for details about rewriting this method. // Note that this interface does not contain the clone method. Therefore, it is impossible to clone an object by implementing this interface. Even if the clone method is called by reflection, it cannot be guaranteed that it will succeed. TestBean testbean3 = null; try {testbean3 = (TestBean) testbean1.clone ();} catch (CloneNotSupportedException e) {e. printStackTrace ();} // IV. deserialization, but the class must implement the serialization interface ObjectOutputStream objOutStream = null; ObjectInputStream objInStream = null; TestBean testbean4 = null; try {File file = new File ("C: \ testbean.txt"); if (! File. exists () {file. createNewFile ();} // objOutStream = new ObjectOutputStream (new FileOutputStream (file); // objOutStream. writeObject (testbean1); objInStream = new ObjectInputStream (new FileInputStream (file); testbean4 = (TestBean) objInStream. readObject ();} catch (Exception e) {e. printStackTrace ();} finally {if (objOutStream! = Null) {try {objOutStream. close () ;}catch (IOException e) {e. printStackTrace () ;}} if (objInStream! = Null) {try {objInStream. close ();} catch (IOException e) {e. printStackTrace () ;}} System. out. println ("testbean1:" + testbean1); System. out. println ("testbean2:" + testbean2); System. out. println ("testbean3:" + testbean3); System. out. println ("testbean4:" + testbean4 );}}

Running result:

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.