The reflection of Java

Source: Internet
Author: User
Tags modifier modifiers

The reflection of Java
First, Java Reflection
Reflection (reflection) is the key to being considered a dynamic language, and the reflection mechanism allows the program to obtain internal information of any class by means of the Reflection API during the execution period.
And can directly manipulate the internal properties and methods of arbitrary objects.
Features provided by the ①java reflection mechanism
Determine the class to which any object belongs at run time
To construct an object of any class at run time
Determine the member variables and methods that any one class has at run time
To invoke member variables and methods of any object at run time
Generating dynamic agents
② reflection-related major APIs:
Java.lang.Class: Represents a class
Java.lang.reflect.Method: Methods for representing classes
Java.lang.reflect.Field: A member variable representing a class
Java.lang.reflect.Constructor: The construction method of the Representative class
Second, class
①class itself is also a class
Java.lang.Class: Is the source of reflection.
We created a class that, by compiling (Javac.exe), generates the corresponding. class file. We then use Java.exe to load (the JVM's class loader)
this. class file, which is loaded into memory, is a runtime class that exists in the cache. Then the runtime class itself is an instance of Class!
1. Each runtime class is loaded only once!
2. Once you have an instance of class, we can do the following:
1) * Create an object of the corresponding runtime class
2) Gets the complete structure of the corresponding runtime class (properties, methods, constructors, inner classes, parent classes, packages, exceptions, annotations 、... )
3) * Call the specified structure (properties, methods, constructors) of the corresponding run-time class
4) Application of Reflection: Dynamic agent
Common methods of ②class class
Static class forname (String name): Loads and returns a class object with the name named
Object Newinstance (): Call the default constructor to return an instance of the class object
String getName (): Returns the name of the entity (class, interface, array class, base type, or void) represented by this class object
Class Getsuperclass (): Returns the Class object of the parent class of the current class object
class [] Getinterfaces (): Gets the interface of the current class object
ClassLoader getClassLoader (): Returns the class loader for this class
Constructor[] GetConstructors (): Returns an array containing some Constructor objects
Field[] GetFields (): Returns an array of Field objects
Method GetMethod (String name,class ... paramtypes): Returns a Method object with a parameter type of Paramtype
③ instantiating class objects (four methods)
1) Premise: If the specific class is known, the method is most safe and reliable, and the program performance is the highest, if the class attribute is obtained.
Example: Class clazz = String.class;
2) Premise: an instance of a class is known, calling the instance's GetClass () method to get the class object
Example: Class clazz = new String (). GetClass ();
3) Premise: A class is known to the full class name, and the class in the classpath, can be obtained through the class class static method Forname (class's full class name), may throw classnotfoundexception
Example: Class clazz = Class.forName ("java.lang.String");
4) Other: loading by the class loader
ClassLoader loader = This.getclass (). getClassLoader ();
Class clazz4 = Loader.loadclass ("java.lang.String");
④ Understanding: The loading process of classes
When the program actively uses a class, if the class has not yet been loaded into memory, the system will initialize the class with the following three steps
1) Read the class file into memory and create a Java.lang.Class object for it. This process is done by the class loader
2) merging the binary data of the class into the JRE
3) The JVM is responsible for class initialization
⑤ Understanding: ClassLoader class Loader
The class loader is used to load classes (class) into memory. The JVM specification defines two types of ClassLoader:
Start the class loader (bootstrap) and the user-defined loader (user-defined class loader).
The JVM generates an initialization loader hierarchy of 3 ClassLoader at run time
1) Boot class loader: written in C + +, is the JVM's own class loader, responsible for the Java Platform Core library, used to load the core class library. The loader cannot get directly
2) Extension Class loader: Responsible for the jar package in the Jre/lib/ext directory or –D java.ext.dirs the jar in the specified directory into the working library
3) System ClassLoader: Responsible for Java–classpath or –D Java.class.path refers to the directory of the class and Jar wrapper into the work, is the most common loader
1. Get a System class loader
ClassLoader ClassLoader = Classloader.getsystemclassloader ();
System.out.println (ClassLoader);
2. Get the parent class loader of the system ClassLoader, the extension class loader
ClassLoader = Classloader.getparent ();
3. Get the parent class loader of the extension ClassLoader, which is the boot class loader
ClassLoader = Classloader.getparent ();
4. Test which class loader the current class is loaded by
ClassLoader = Class.forName ("Exer2. Classloaderdemo "). getClassLoader ();
5. Test which class loader is loaded by the object class provided by the JDK
ClassLoader = Class.forName ("Java.lang.Object"). getClassLoader ();
*6. A primary method for the ClassLoader: getResourceAsStream (String str): Gets the input stream of the specified file under the Classpath
InputStream in = This.getclass (). getClassLoader (). getResourceAsStream ("exer2\\test.properties");
Iii. creating a Class object and getting the full structure of the class
① creating objects for classes: calling the Newinstance () method of a Class object
Requirements: 1) The class must have a constructor that has no arguments.
2) The constructor of the class must have sufficient access rights.
If there is no parameterless constructor, the operation can only be instantiated when the constructor in the class is explicitly invoked at the time of operation, and the parameters are passed in. The steps are as follows:
1) The constructor for the specified formal parameter type of this class is obtained through Class Getdeclaredconstructor (class ... parametertypes)
2) pass an array of objects into the constructor's formal parameters, which contains each parameter required in the constructor.
3) Call the constructor class's Newinstance (Object ... args)
② the full structure of a class by reflection
②① gets the properties of the corresponding run-time class Java.lang.reflect.Field
1) field[] GetFields (): Can only get properties declared as public in the runtime class and its parent class
2) field[] Getdeclaredfields (): Gets all the properties declared by the runtime class itself
3) Field GetField (String fieldName): Gets the property named FieldName of the specified property declared as public in the runtime class
4) Field Getdeclaredfield (String fieldName): Gets the property named FieldName specified in the run-time class, which can get all the properties, including the private property
5) Gets the contents of the various parts of the property (permission modifier variable type variable name)
1. Get permission modifiers for each property
int i = Feild.getmodifiers (); Returns an integer representing the modifier
String str1 = Modifier.tostring (i); converts a numeric value to a string by Modifier's toString ()
2. Get the type of the property
Class type = Feild.gettype (): Returns the class object of the property type
3. Get the property name
String str = feild.getname (); Returns the name of the property
6) Modify the property value method one (public String name;)
Class clazz = Person.class;
1. Get the specified property GetField (String fieldName): Gets the property named FieldName of the specified property declared as public in the runtime class
Field name = Clazz.getfield ("name");
2. Creating objects for the runtime class
Person P = (person) clazz.newinstance ();
SYSTEM.OUT.PRINTLN (P);
3. Assign a value to the specified property of the run-time class
Name.set (P, "Jerry");
7) Modify Attribute value method two (private int age;)
Getdeclaredfield (String fieldName): Gets the property named FieldName specified in the run-time class
Field age = Clazz.getdeclaredfield ("Age");
Because of the restriction of the property permission modifier, in order to ensure that the property can be assigned a value, it is necessary to make this property operational before the operation.
Age.setaccessible (TRUE);
Age.set (p,10);
②② gets the method of the run-time class Java.lang.reflect.Method
1) method[] GetMethods (): Gets all the methods declared public in the runtime class and its parent class
2) method[] Getdeclaredmethods (): Gets all the methods declared by the runtime class itself
3) Method GetMethod (String methodname,class ... params): Gets the specified method declared as public in the run-time class
4) Method Getdeclaredmethod (String methodname,class ... params): Gets the specified method declared in the run-time class
5) Gets the contents of the various parts of the method (annotation permission modifier return value type method name parameter list exception)
1. Annotations
annotation[] ann = Method.getannotations ();
2. Permission modifiers
String str = modifier.tostring (Method.getmodifiers ());
3. Return value type
Class returntype = Method.getreturntype ();
4. Method name
String str = method.getname ();
5. Formal parameter list
class[] params = Method.getparametertypes ();
6. Exception types
class[] Exps = Method.getexceptiontypes ();
6) Call the method specified in the run-time class one [public void Show ()]
Class clazz = Person.class;
GetMethod (String methodname,class ... params): Gets the specified method declared as public in the run-time class
method = Clazz.getmethod ("show");
Person P = (person) clazz.newinstance ();
Call the specified method: Object Invoke (Object Obj,object ... obj)
Object returnval = M1.invoke (p); : Returns the return value of the calling method
System.out.println (ReturnVal);

Calls to static methods in run-time classes [public static void info ()]
method = Clazz.getmethod ("info");
Method.invoke (Person.class);
7) Call the method specified in the run-time class two [private int show (String nation,int Age)]
Getdeclaredmethod (String methodname,class ... params): Gets the specified method declared in the run-time class
method = Clazz.getdeclaredmethod ("display", String.class,int.class);
Because of the restriction of the property permission modifier, in order to ensure that the property can be assigned a value, it is necessary to make this property operational before the operation.
Method.setaccessible (TRUE);
Object value = Method.invoke (P, "CHN", 10);
System.out.println (value);
②③ gets the constructor of the run-time class Java.lang.reflect.Constructor
1) public constructor<t>[] GetConstructors () returns all public constructor methods for the class represented by this class object.
2) public constructor<t>[] Getdeclaredconstructors () returns all the constructor methods for the class declaration represented by this class object
3) Public constructor<t> getconstructor (class<?> ... parametertypes): constructor to return the specified public
4) Public constructor<t> getdeclaredconstructor (class<?> ... parametertypes): Returns the specified constructor declared in the class. Include private constructor
5) Call the constructor specified in the run-time class
String className = "com.lang.String";
Class clazz = Class.forName (className);
Creates an object for the corresponding run-time class. Using Newinstance () is actually the constructor that invokes the null parameter of the runtime class.
To be able to create a success: ① requires the corresponding runtime class to have a constructor with null parameters. The permissions of the ② constructor are sufficient.
Object obj = clazz.newinstance ();
String p = (string) obj;
6) Call the constructor specified in the run-time class
String1 className = "Com.lang.String1";
Class clazz = Class.forName (className);

Constructor cons = Clazz.getconstructor (String.class,int.class);
String1 p = (String1) cons.newinstance ("Small Three", 20);

Constructor cons = Clazz.getdeclaredconstructor (String.class,int.class);
Cons.setaccessible (TRUE);
String1 p = (String1) cons.newinstance ("Small Three", 20);
②④ getting annotations for run-time classes
Class clazz = String.class;
annotation[] anns = clazz.getannotations ();
for (Annotation A:anns) {
System.out.println (a);
}
②⑤ get the package that the runtime class resides in
Class clazz = String.class;
Package pack = Clazz.getpackage ();
SYSTEM.OUT.PRINTLN (Pack);

②⑥ an interface to get the implementation of a run-time class
Class clazz = Person.class;
Class[] interfaces = Clazz.getinterfaces ();
for (Class i:interfaces) {
System.out.println (i);
}

②⑦*. Getting generics for the parent class of the runtime class
Class clazz = Person.class;
Type type1 = Clazz.getgenericsuperclass ();

Parameterizedtype param = (parameterizedtype) type1;
type[] ars = param.getactualtypearguments ();

System.out.println ((Class) ars[0]). GetName ());
②⑧ getting the parent class with generics
Class clazz = Person.class;
Type type1 = Clazz.getgenericsuperclass ();
System.out.println (type1);

②⑨ getting the parent class of the run-time class
Class clazz = Person.class;
Class superclass = Clazz.getsuperclass ();
System.out.println (superclass);

The reflection of Java

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.