Dark Horse Programmer -- [Java high-tech] -- reflection mechanism, java high-tech
---------- Android training, java training, and hope to communicate with you! ----------
I. Overview
1. Java reflection mechanism: refers toIn running status",Any classAll attributes and methods in this class can be known.Any objectAnd can call any of its methods and attributes. The information obtained dynamically and the function of calling methods of objects dynamically is called the reflection mechanism of java.
2. the Java reflection mechanism provides the following functions:
(1) determine the class to which any object belongs during runtime
(2) construct the object of any class at runtime
(3) When running, judge the member variables and methods of any class (implemented through reflection ).
(4) Call the method of any object at runtime (Note: The premise is that it is at runtime, not during compilation)
3. Reflection: Refers to anatomy of classes, and maps various components in Java classes into corresponding java classes.
A Java Class is represented by a Class object. The components of a Class: member variables, methods, constructor methods, packages, and other information are also represented by Java classes. The Class of the java Class provides a series of methods to obtain the variables, methods, constructor, modifiers, packages, and so on. These information is represented by the Instance Object of the corresponding Class, they are Field, Method, Contructor, and Package.
II. The cornerstone of reflection-ClassClass
(1) Overview
All Class files share common attributes, so you can extract them up and encapsulate these common contents into a Class. This Class is called Class. The Class contains attributes such as field, method, and construction ).
(2) ClassAnd classDifference
1. class: A class in Java is used to describe the commonality of a class of things. The class has no attributes, and the value of this attribute is determined by the instance object of this class, different instance objects have different attribute values.
2. Class: indicates that each Java Class in a Java program belongs to the same Class and is a Java program Class. These classes are called classes. Class is the general term for various Java classes in Java programs. It is the cornerstone of reflection and uses reflection through Class classes.
(3) obtain the ClassThree methods of object:
1. The getClass () method in the Object class (this method must specify the specific class and create an Object, which is troublesome), for example:
Person p = new Person ();
Class clazz = p. getClass ();
2. Any data type has a static attribute. class to obtain the corresponding Class Object (this method is relatively simple, but it is still necessary to explicitly use static members in the class, not enough extension ).
Class clazz = Person. class;
3. The forName () method in the Class can be used for better scalability (this method can obtain the Class object through the "string name" of the given Class, and is more extended)
String className = "package name. Class Name ";
Class clazz = Class. forName (className );
// * How do I generate an empty parameter object?
Object obj = clazz. newInstance ();
(4) Basic ClassObject
1. Nine predefined classes:
(1) bytecode objects of eight basic types (byte, short, int, long, float, double, char, and boolean) and void. class whose return value is void.
(2) Integer. TYPE: indicates the Class instance of the basic TYPE int, which is equal to int. class. The bytecode of the basic data TYPE can be expressed by the TYPE constant in the corresponding packaging class.
2. All types in the source program have their own Class instance objects, such as int []. class. Class instance objects of the array type, which can be represented by Class. isArray.
(5) ClassMethods in the class
1. static Class forName (String className): 1. Return the Class object associated with the Class or interface of the given String name.
2. Class getClass (): Class returned when the Object is running, that is, the Class Object is the bytecode Object.
3. Constructor getConstructor (): returns the Constructor object, which reflects the specified public Constructor of the Class Object.
4. Field getField (String name): returns a Field object, which indicates the specified public member Field of the Class object or interface.
5. Field [] getFields (): returns an array containing some Field objects, representing the Member fields in the class.
6. Method getMethod (String name, Class... ParameterTypes): returns a Method object, which indicates the specified public member Method of the Class represented by this Class object.
7. Method [] getMehtods (): returns an array containing some Method objects, which is a common member Method in the class.
8. String getName (): returns the object name represented by this Class object in the String format.
9. String getSuperclass (): returns the name of the superclass of the Class represented by this Class.
10. boolean isArray (): determines whether the Class object represents an array.
11. boolean isPrimitive (): determines whether the specified Class object is of a basic type.
12. T newInstance (): Creates a new instance of the Class represented by this Class object.
(6) sample code:
Package cn. itheima; class Person {private String name; public int age; public Person () {System. out. println ("Person run");} public Person (String name, int age) {this. age = age; this. name = name;} public String toString () {return name + ":" + age;} public class ClassDemo {public static void main (String [] args) throws Exception {// obtain the full name String of the class String className = "cn. itheima. person "; // obtain the Class Object Class clazz = Class of the Person Class. forName (className); // obtain the instance Person p = (Person) clazz of the class's no-argument constructor using the newInstance method. newInstance ();}}
Iii. ConstructorClass
(1) Overview
Constructor represents a Constructor of a class.
(2) constructor
1. Obtain all Constructor cons = Class. forName ("java. lang. String"). getConstructors ();
2. Obtain a Constructor con = String. class. getConstructor (String. class, int. class );
(3) create an Instance Object
1. Common method: String str = new String (new StringBuffer ("abc "));
2. Reflection Method: String str = (String) constructor. newInstance (new StringBuffer ("abc "));
Note:
(1) When creating an instance, the parameter list in the newInstance method must be consistent with the parameter list in the getConstructor method.
(2) newInstance (): constructs an instance object and constructs an object every time a call is made.
(3) the advantage of using the Constructor Class to create Class instances is that you can specify the Constructor, while the Class can only create Class instance objects using the non-argument Constructor.
(4) Sample Code
Package cn. itheima; class Person {private String name; public int age; public Person () {System. out. println ("Person run");} public Person (String name, int age) {this. age = age; this. name = name;} public String toString () {return name + ":" + age ;}// use the Constructor object to create the class instance method public static void ConstructorDemo () throws Exception {// get the Class Object of the Person Class String name = "cn. itheima. person "; Class clazz = Class. forName (name); // Class clazz = Person. class; // obtain the Constructor con = clazz. getConstructor (String. class, int. class); Person p = (Person) con. newInstance ("lisi", 30); System. out. println (p. toString ());}
Iv. FieldClass
(1) Overview:The Field class represents a member variable in a class.
(2) Method
1. Field getField (String s): Only public and parent classes can be obtained.
2. Field getDeclaredField (String s): obtains any member variables in the class, including private
3. setAccessible (ture): // if it is a private field, you must first cancel the permission check for this private field. Also known as brute-force access.
4. set (Object obj, Object value): set the Field represented by this Field Object on the specified Object variable to the specified new value.
5. Object get (Object obj): return the value of the Field on the specified Object.
(3) Sample Code
1 package cn. itheima; 2 class Person {3 private String name; 4 public int age; 5 public Person () {6 System. out. println ("Person run"); 7} 8 public Person (String name, int age) {9 this. age = age; 10 this. name = name; 11} 12 public String toString () {13 return name + ":" + age; 14} 15} 16 // get the member variable 17 public static void getPersonField () throws Exception {18 // if you want to assign a value to this variable, you must first have an object. 19 Class clazz = Class. forName ("cn. itheima. person "); 20 Person p = (Person) clazz. newInstance (); 21 // obtain all member variables 22 Field [] fs = clazz. getFields (); 23 for (Field f: fs) {24 System. out. println (f); 25} 26 // get the specified member variable 27 Field fage = clazz. getField ("age"); 28 Field fname = clazz. getDeclaredField ("name"); 29 // display the changed value 30 fage. set (p, 20); 31 System. out. println (fage. get (p); 32 // brute-force access to the private variable 33 fname. setAccessible (true); 34 fname. set (p, "zhangsan"); 35 System. out. println (fname. get (p); 36}
V. MethodClass
(1) Overview: The Method class represents the Member methods in a class. To call a method on an object, you must first obtain the method and then call it on an object.
(2) Method
Method [] getMethods (): obtains only the methods in the public and parent classes.
Method [] getDeclaredMethods (): obtain private information contained in this class.
Method getMethod ("Method name", parameter. class (null can be written if it is a null parameter ));
Object invoke (Object obj, parameter): Call Method
Note: ① invoke method: if the underlying layer is static, you can ignore the specified obj parameter and fill it with null. ② If the "form parameter" required by the underlying method is 0, the length of the provided args array can be 0 or null.
(3) Obtain methods in the class
1. Common method: Object Name. function. Such as str. charAt (int index );
2. reflection mode:
Method MethodCharAt = Class. forName ("java. lang. String"). getMethod ("charAt", int. class );
3. Reflection calls the underlying method: charAtMethod. invoke (str, int index );
Note: If the first parameter of the invoke () Method passed to the Method object is null, the Method object corresponds to a static Method.
(4) Sample Code Application
Package cn. itheima; class Person {private String name; public int age; public Person () {System. out. println ("Person run");} public Person (String name, int age) {this. age = age; this. name = name;} public String toString () {return name + ":" + age;} public static void getPersonMethod () throws Exception {// if you want to obtain a method, you must first have an object. Class clazz = Class. forName ("cn. itheima. person "); // obtain all methods. Method [] methods = clazz. getMethods (); // obtain only the public and parent classes. // Methods = clazz. getDeclaredMethods (); // obtain all methods in this class, including private. For (Method method: methods) {System. out. println (method);} // obtain a single Method, method me = clazz. getMethod ("toString", null); Object returnVaule = me. invoke (p, null); System. out. println (returnVaule );}
Vi. array reflection
(1) Overview
1. Arrays with the same dimension and element type belong to the same type and have the same Class instance object. The name of the array bytecode: an abbreviation of the [and array corresponding type, for example, the name of the int [] array is: [I
2. Basic Types of one-dimensional arrays can be used as objects and cannot be used as objects []. Non-basic types of one-dimensional arrays can be used as objects, it can also be used as the Object [] type.
3. How to obtain the type of an element in an array?
For example: Object [] obj = new Object [] {"ABC", 1}; you cannot obtain the specific type of an array. You can only obtain the type of an element, for example: obj [0]. getClass (). getName () returns java. lang. string.
4. The Arrays. asList () method is different when int [] is String. It saves int [] as an object element to the list set. Every String element in the String [] array is stored as an object in the list set.
5. the Array tool class (java. lang. reflect. Array) is used to perform the reflection operation on the Array. It provides a way to dynamically create and access the Java Array: for example:
Array. getLength (Object obj); // gets the length of the Array.
Array. get (Object obj, int x); // obtain the elements in the Array
(2) array reflection code example
1 import java. lang. reflect. array; 2 import java. util. arrays; 3 public class ArrayReflect {4 public static void main (String [] args) {5 int [] a1 = new int [] {1, 2, 3 }; 6 int [] [] a2 = new int [2] [3]; 7 String [] a3 = new String [] {"a", "B ", "c"}; 8 Object obj1 = a1; 9 Object obj2 = a3; 10 Object obj3 = a4; 11 // The Array tool class is used to complete the Array reflection operation. For example, print any number 12 printObject (a1); 13 printObject (a4); 14 printObject ("abc "); 15} 16 // print any number 17 private static void printObject (Object obj) {18 Class clazz = obj. getClass (); 19 // if the input is an array, it traverses 20 if (clazz. isArray () {21 int len = Array. getLength (obj); // Method 22 for obtaining the Array length using the Array tool class (int x = 0; x <len; x ++) {23 System. out. println (Array. get (obj, x); // Array tool obtains Array elements 24} 25} 26 else27 System. out. println (obj); 28} 29}
VII. Functions of reflection-implement FRAMEWORK Functions
(1) Overview
1. Framework: A method for calling Java classes through reflection. The framework is like a real estate company building a house, doors and windows, air conditioning, and other internal decoration are all installed by the user. A house is a framework. users need to use this framework to secure doors and windows and put them in the framework provided by real estate agents.
Note: The difference between the framework and the tool class is that the tool class is called by the user class, and the framework is the class provided by the user.
2. core issues to be addressed by the Framework
When we write the framework, the called class has not yet appeared, so the framework cannot know the name of the class to be called, so it is impossible to directly create an instance object of a class in the program, instead, we need to use reflection.
(2) Steps for creating a simple framework:
1. Create a configuration file in the java project panel of Eclipse:
"Right-click" -- "New" -- select "File", name file name config. properties, and write configuration information. For example, className = java. util. ArrayList, the configuration key is on the right side of the equal sign, and the value is on the right side.
2. Code implementation: load the file:
① To read the file to the read stream, write the path of the configuration file (relative or absolute path ). For example, InputStream ips = new FileInputStream ("config. properties ");
② Use the load () method of the Properties class to load the data in the stream into the set.
③ Disable stream resources: Disable stream reading because the data in the stream has been loaded into the memory.
3. Get the className through the getProperty () method, that is, the configured value, that is, a class name.
4. Use reflection to create the newInstance () object ().
5. Execute the main program function
8. manage resources and configuration files by class loaders
(1) Overview
1. class Loader: loads. class files into the memory, or loads information in common files into the memory.
2. file loading details:
(1) eclipse will compile all. java files in the source program into. class files and put them in the directory specified by classPath. In addition, non-. java files are copied to the directory specified by. class. When running, the. class file is executed.
(2) Place the configuration file in the. class directory and package it together. The class loader will load it together.
3. Use the class loader to load the "resource file".
(1) The ClassLoader of the Class Loader is used to load the data into the memory. That is, the getClassLoader () method is used to obtain the class loader, and then the getResourceAsStream (String name) method of the Class Loader is used, load the configuration file (resource file) into the memory. To use the class loader to load the configuration file, you must write the package name in the configuration file together. This method only supports reading.
(2) the Class also provides the getResourceAsStream method to load resource files. In fact, it calls the ClassLoader method internally. In this case, the configuration file is relative to the current directory of the class file. That is to say, the package name can be omitted before the configuration file.
For example, class name. class. getResourceAsStream ("resource file name ")
4. Path of the configuration file:
(1) Use the absolute path and the getRealPath () method to calculate the specific directory
Generally, first obtain the User-Defined directory and add your own internal path. You can use the getRealPath () method to obtain the file path. To modify the configuration file, you need to store it in the configuration file, so you need to obtain its absolute path. Therefore, the configuration file should be placed inside the program.
(2) name path problems:
① If the configuration file has nothing to do with the classPath directory, you must write the absolute path,
② If the configuration file is related to the classPath directory, that is, in the classPath directory or in its subdirectory (generally the resource folder resource), you must write the relative path, because it knows which package it belongs to, it is relative to the current package.
(2) Sample Code
import java.io.InputStream;import java.util.Collection;import java.util.Properties;class ClassLoaderDemo { public static void main(String[] args) throws Exception{ Properties props = new Properties(); InputStream ips = ClassLoaderDemo.class.getResourceAsStream ("/cn/itheima/day01/config.properties"); props.load(ips); ips.close(); String className = props.getProperty("className"); Class clazz = Class.forName(className); Collection collection = (Collection)clazz.newInstance(); collection.add("abc"); collection.add("def"); collection.add("ghk"); collection.add("usa"); System.out.println(collection.size()); }}
---------- Android training, java training, and hope to communicate with you! ----------
Ask who has a full set of java teaching videos for black horse programmers, Zhang Xiaoxiang and Bi Xiangdong
Edu.csdn.net/main/video.shtmlpackage you are satisfied with, from basic to advanced, there is no missing. Hope you can make good use of it! At the same time, I wish you the best effort for the development of the Chinese software industry!
[2012 dark horse programmer] JAVA basics 02 [Top] rar and [2012 dark horse programmer] JAVA basics 02 [bottom] rar decompression Password
Www.itheima.com/main/feature/bxd_25.shtml
Download the password for the last two days.
Other: www.itheima.com/main/studyline/heimaline.html
Hope to help you