1 using newinstance () is actually called the constructor that runs the time-space parameter
Note that the constructor's permission modifier is sufficient, and that there must be a constructor for the null parameter.
2 calling the specified property method constructor
Packagelianxi1;ImportJava.lang.reflect.Constructor;ImportJava.lang.reflect.Field;Importjava.lang.reflect.InvocationTargetException;ImportJava.lang.reflect.Method;Importorg.junit.Test; Public classTestReflection2 {@Test Public voidTest1 ()throwsclassnotfoundexception, SecurityException, Nosuchfieldexception, Instantiationexception, illegalaccessexception {//1. Get the properties of the Run classString str = "LIANXI1." Person "; Class Clazz=class.forname (str); Field F1= Clazz.getfield ("name"); //If the property is privateField F2 = Clazz.getdeclaredfield ("Age"); F2.setaccessible (true); //2. Creating an object that runs a classObject obj =clazz.newinstance (); Person P=(person) obj; SYSTEM.OUT.PRINTLN (P); //3. Assigning a value to a propertyF1.set (P, "Tian"); F2.set (P,25); SYSTEM.OUT.PRINTLN (P); } @Test Public voidTest2 ()throwsclassnotfoundexception, SecurityException, Nosuchmethodexception, Instantiationexception, Illegalaccessexception, IllegalArgumentException, invocationtargetexception{//2. Invoke the method specified in the runtime classClass clazz = person.class; Method M1= Clazz.getmethod ("Show"); Person P1=(person) clazz.newinstance (); Object obj= M1.invoke (p1);//if the static method is changed to M1.invoke (Person.class)System.out.println (obj); Method m2= Clazz.getdeclaredmethod ("Display", String.class,int.class); M2.setaccessible (true); Object Obj2= M2.invoke (P1, "Yu", 22); System.out.println (OBJ2); } @Test Public voidTest3 ()throwsSecurityException, Nosuchmethodexception, IllegalArgumentException, Instantiationexception, Illegalaccessexception, invocationtargetexception{//3. Invoke the constructed constructor to create the object of the runtime classClass clazz = person.class; Constructor Con= Clazz.getdeclaredconstructor (String.class,int.class); Con.setaccessible (true); Person P2= (person) con.newinstance ("Wuming", 21); System.out.println (p2); }}
Creates an object of the run-time class, invoking the specified property method constructor