To makeProgramIt has higher flexibility and configurability. during development, we often use reflection to create a class instance, that is, to obtain an object of a class! The common practice is to use the class. newinstance is obtained. But this method has a bad point, that is, it can only create an object without a parameter constructor. If the constructor has a parameter, it cannot do anything; the solution is to first obtain the constructor with parameters through the class of this class, and then create an instance through the constructor and the initialization parameters for passing the example! The following is a demo of the above practice:
Entity class:
-
- PackageReflect;
-
-
- Public ClassDuck {
-
- PrivateInteger weight;
-
- PrivateString name;
-
-
- PublicDuck (){
-
- System. Out. println ("No parameter is called");
-
- }
-
-
- PublicDuck (string name ){
-
- Name = Name;
-
- System. Out. println ("One Parameter called");
-
- }
-
- PublicDuck (string name, integer weight ){
-
- Name = Name;
-
- Weight = weight;
-
- System. Out. println ("Two Parameter called");
-
- }
-
- }
-
- PackageReflect;
-
- ImportJava. Lang. Reflect. constructor;
-
- ImportJava. Lang. Reflect. invocationtargetexception;
-
-
- Public ClassExetest {
-
- Public Static VoidMain (string [] ARGs ){
-
- <Span style ="Color: #000000"> Class CLS = duck.Class; </Span>
-
-
- Class conargs [] = {string.Class, Integer.Class};
-
-
- Try{
-
- <Span style ="Color: #000000"> Constructor = Cls. getconstructor (conargs); </span>
-
-
- String name ="ABC";
-
- Integer Weight =NewINTEGER (1056);
-
- Object initargs [] = {name, weight };
-
- <Span style ="Color: #000000"> Constructor. newinstance (initargs); </span>
-
-
-
- }Catch(Securityexception e ){
-
-
- E. printstacktrace ();
-
- }Catch(Nosuchmethodexception e ){
-
- E. printstacktrace ();
- }Catch(Illegalargumentexception e ){
-
- // Todo auto-generated Catch Block
-
- E. printstacktrace ();
-
- }Catch(Instantiationexception e ){
- // Todo auto-generated Catch Block
-
- E. printstacktrace ();
-
- }Catch(Illegalaccessexception e ){
-
- // Todo auto-generated Catch Block
-
- E. printstacktrace ();
- }Catch(Invocationtargetexception e ){
-
- // Todo auto-generated Catch Block
-
- E. printstacktrace ();
-
- }
-
-
- }
-
-
- }