Several common methods of creating objects in Java

Source: Internet
Author: User

Several common ways to create objects in Java:

1. Create an object with the New keyword

2, using the reflection mechanism of Java, through Java.lang.Class or java.lang.reflect.Constructor to create objects

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

4. Implement serialization Serialiable interface, create object by deserialization, ObjectInputStream ReadObject () method

5. String str= "ABC" is created directly by the JVM or using the string operator "+" string str1 = "a" + "BC" created by the JVM

Creating an Object class Testbean.java

 Packagetest.createobj;Importjava.io.Serializable; Public classTestbeanImplementscloneable,serializable{/**     *      */    Private Static Final LongSerialversionuid = -6896355094290356656l; PrivateString ID; PrivateString name;  PublicTestbean (string ID, string name) { This. ID =ID;  This. Name =name; }     Public voidsetName (String name) { This. Name =name; }     PublicString GetName () {returnname; }     Public voidsetId (String id) { This. ID =ID; }     PublicString getId () {returnID; } @OverrideprotectedObject Clone ()throwsclonenotsupportedexception {return Super. Clone (); } @Override PublicString toString () {return Super. toString () + "" +id+ "" +name; }}

Create a test class Createobjtest.java

 Packagetest.createobj;ImportJava.io.File;ImportJava.io.FileInputStream;ImportJava.io.FileOutputStream;Importjava.io.IOException;ImportJava.io.ObjectInputStream;ImportJava.io.ObjectOutputStream;ImportJava.lang.reflect.Constructor; Public classCreateobjtest {/**     * @paramargs*/@SuppressWarnings ("Rawtypes")     Public Static voidMain (string[] args) {//First, new keyword to create an objectTestbean Testbean1 =NewTestbean ("1", "Zhang San haha"); //second, reflection mechanismTestbean testbean2 =NULL; Try{Class<?> clazz = Class.forName ("Test.createObj.TestBean"); //java.lang.InstantiationException exceptions are reported when a constructor with a parameter in the class does not have a parameterless constructor//you need to add the parameterless constructor in the class//testbean2 = (Testbean) clazz.newinstance (); //or a parameter constructor that takes a reflection to get a class to instantiate an object with a parametric constructorClass[] Paramtypes = {String.class, String.class}; Constructor Constor=Clazz.getconstructor (paramtypes); Testbean2= (Testbean) constor.newinstance ("2", "John Doe"); } Catch(Exception e) {e.printstacktrace (); }                //cloning but the class must implement the Cloneable interface and override the Clone method in the class//The jdl1.6 Chinese API says this://invoking the Clone method of Object on an instance that does not implement the Cloneable interface causes the clonenotsupportedexception exception to be thrown. //by convention, a class that implements this interface should use a public method to rewrite the Object.clone (which is protected). //See Object.clone () For more information about overriding this method. //Note that this interface does not contain a clone method. Therefore, it is not possible to clone an object because it implements this interface. Even if the Clone method is a reflexive call, there is no guarantee that it will succeed. Testbean testbean3 =NULL; Try{testbean3=(Testbean) Testbean1.clone (); } Catch(clonenotsupportedexception e) {e.printstacktrace (); }                //four, deserialization but class to implement the serialization interfaceObjectOutputStream Objoutstream =NULL; ObjectInputStream Objinstream=NULL; Testbean Testbean4=NULL; Try{File File=NewFile ("C:\\testbean.txt"); if(!file.exists ())            {File.createnewfile (); }//Objoutstream = new ObjectOutputStream (new FileOutputStream (file));//Objoutstream.writeobject (testbean1);Objinstream =NewObjectInputStream (Newfileinputstream (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); }}

Operation Result:

Several common methods of creating objects in Java

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.