Reflection is the acquisition of a runtime class to obtain all the structure of a class, such as properties, methods, variables, etc.
1. How to create class instances first
Class class = Person.clsss;
1.1 Procedure: After the source file is compiled (Javac.exe). To get one or more. class files, after running (java.exe) This step, you need to load the class (via the JVM loader) into the in-memory cache, and each cached file is an instance of class
Java.lang.Class is the source of the reflection, and the next classes are under the Java.lang.reflect sub-package.
1.2 Instantiate the class class in three ways:
1 calling the Class property of the run-time classes
Class clazz1 = Person.class;
2 Call the GetClass method by running the Shilei object
Person p = new person ();
Class Clazz2=p.getclass ();
3 by calling the class's static method Forname (String ClassName) method will be reported classnotfoundexception
String className = "Com.test.Person";
Class clazz3 = Class.forName (className);
2. After you have the class instance, you can create the runtime object for the class, and get the complete class structure of the class, including: properties, methods, constructors,
Packages, parent classes, interfaces, generics, annotations, exceptions, inner classes
such as: method[] m1 = Class.getmethods (); Gets the method that the permission declared in the corresponding runtime class is public
Method[] m2= class.gettdeclaredmethods (); Gets all the methods of the corresponding run-time class, including private and protected
@Testpublic void Test1{class clazz = Class.forName ("Com.test.java.Animal"); object object = Clazz.newinstance (); Animal a = (Animal) object; System.out.println (a);} @Testpublic void Test2{class clazz = Animal.class; Constructor Constructor = Clazz.getdeclaredconstructor (String.class,int.class); constructor.setaccessible (true); Animal Animal = (Animal) constructor.newinstance ("Tom", 20); System.out.println (a);}
You can also invoke the developed structure of the corresponding run-time class
Java Reflection mechanism