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 );
Five ways to create objects in Java