Person.java
Package com.feng.reflect;
Import java.util.List;
public class Person {public
String name= "AAA";
Public person () {
System.out.println (' person ');
}
Public person (String name) {
System.out.println (name);
}
Public person (String name,int password) {
System.out.println (name+ ":" +password);
}
Private person (List list) {
System.out.println ("list");
}
Demo.java
Package com.feng.reflect;
Import java.awt.List;
Import Java.lang.reflect.Constructor;
Import java.lang.reflect.InvocationTargetException;
Import java.util.ArrayList;
Import Org.junit.Test; The constructor of the reflection class, which creates the object of the class public class Demo2 {//Reflection class constructor: Public person () @Test public void Test1 () throws Classnotfoundexcep tion, nosuchmethodexception, SecurityException, Instantiationexception, Illegalaccessexception,
IllegalArgumentException, invocationtargetexception{Class clazz = Class.forName ("Com.feng.reflect.Person");
Constructor C = clazz.getconstructor (null);
person who = (person) c.newinstance (null);
System.out.println (Person.name); }//Reflection class constructor: Public person (String name) @Test public void Test2 () throws exception{class Clazz = Class.forName ("com.
Feng.reflect.Person ");
Constructor C = Clazz.getconstructor (String.class);
Person P = (person) c.newinstance ("xxx");
System.out.println (P.name); }//Reflection class constructor: Public person (String name,int password) @Test public voiD test3 () throws exception{Class clazz = Class.forName ("Com.feng.reflect.Person");
Constructor C = Clazz.getconstructor (String.class,int.class);
Person P = (person) c.newinstance ("xxx", 12);
System.out.println (P.name); //private person (list list) @Test public void Test4 () throws exception{Class clazz = Class.forName ("Com.feng.refl Ect.
Person ");
Constructor C = Clazz.getdeclaredconstructor (List.class);
C.setaccessible (TRUE);//violent reflection,,,, need attention.
Person P = (person) c.newinstance (new ArrayList ());
System.out.println (P.name); Another way to create an object @Test public void Test5 () throws exception{Class clazz = Class.forName ("Com.feng.reflect.Person")
;
Person P = (person) clazz.newinstance ()//In fact, the principle is to reflect the class's parameterless constructor to construct,//This is why when you create a parameter constructor, be sure to create a parameterless constructor
System.out.println (P.name);
}
}