Five ways to create objects in Java

Source: Internet
Author: User
Tags shallow copy

Recently in the study of Java knowledge, through the Internet to look at the information, found that the original understanding of something not deep, gradually understand some. The use of objects, in the process of writing software is necessary, do not know whether people like me, almost all use new to create. So, the question is, how many ways does Java have to create objects?

  • Created with the new keyword.
  • You can use the class's Newinstance () method, such as the person class, to create an object, but you cannot call the private constructor in the following two ways, and you must include the parameterless constructor in the class of the constructed object , or you will get an error.
     Public classPerson {/**     *      */    Private Static Final LongSerialversionuid = 10L; String name= "Jack";  PublicPerson () { This. Name = name + "Ma"; System.out.println ("Construct Person"); }        PrivatePersonintAintb) {System.out.println ("A:" +a+ "B:" +b); } @Override PublicString toString () {returnname; }} Method One//here the Testreflect is the package name, the person class is under this packageClass clazz = Class.forName ("Testreflect.person");p Erson p=(person) clazz.newinstance (); method two person P=person.class. newinstance ();

  • using the Newinstance method of the constructor class, this method belongs to reflection, can call any of the scope's constructors, private can also, and the class constructor that creates the object can be arbitrary.
    // call the parameterless constructor in the way a person p = person. class . Getdeclaredconstructor (). newinstance (); // call the parameterless constructor, mode two Constructor C1=person. class . Getdeclaredconstructor (); C1.setaccessible (true);p Erson p= (person) C1.newinstance ();  

    Here you think, when calling the parameterless constructor, What is the difference between one and two ways? Everyone should see c1.setaccessible (TRUE); This code, the definition of the View method contains the following: A value of True Indicates that the reflected object should suppress Java language access checking when it was used, meaning true when forbidden to verify authorization, in other words understand That is, the private non-parametric constructs can also be called. This is the difference between mode one and mode two, the way a private scope is modified, the error will be.

     //  Call the parameter constructor  Constructor c1=person.< Span style= "COLOR: #0000ff" >class . Getdeclaredconstructor (new  class[] { Span style= "COLOR: #0000ff" >int . class , int . class   =person. class . Getdeclaredconstructor (int . class , int . class ); 
      • Public constructor<t> getdeclaredconstructor (class<?> ... parametertypes)                                      throws Nosuchmethodexception,                                             SecurityException
        • Parameters:
          parameterTypes-The parameter array
          Returns:
          The object for the constructor with the
          Constructor specified parameter list
          incoming parameter is an array.

  • How to use clone: Whenever we invoke the Clone method of an object, the JVM creates a new object that copies the contents of the previous object, and creates the object with the Clone method without invoking any constructors . To use the Clone method, the class that created the object must implement the Cloneable interface and implement its definition of the Clone method. About clone can refer to my reproduced Java deep copy and shallow copy.
  • Use deserialization: When we serialize and deserialize an object, the JVM creates a separate object for us, and when deserializing, the JVM creates the object and does not call any constructors . In order to deserialize an object, the corresponding class needs to implement the serializable interface, enclosing a specific implementation code.
    ImportJava.io.FileInputStream;ImportJava.io.FileOutputStream;ImportJava.io.ObjectInputStream;ImportJava.io.ObjectOutputStream;Importjava.io.Serializable; Public classPeopleImplementsserializable{PrivateString name;  Publicpeople () { This. Name = "6 points a June"; System.out.println ("Construct people"); } @Override PublicString toString () {return  This. Name; }         Public Static voidMain (string[] args) {people P=Newpeople ();        SYSTEM.OUT.PRINTLN (P); ObjectOutputStream Oos=NULL; ObjectInputStream Ois=NULL; Try{FileOutputStream fos=NewFileOutputStream ("Test.out"); Oos=NewObjectOutputStream (FOS);            Oos.writeobject (P);        Oos.close (); } Catch(Exception e) {e.printstacktrace ();        } people p1; Try{FileInputStream fis=NewFileInputStream ("Test.out"); Ois=NewObjectInputStream (FIS); P1=(People) ois.readobject ();        System.out.println (p1); } Catch(Exception e) {e.printstacktrace (); }    }}

Five ways to create 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.