Java BASICS (11) ----- reflection mechanism of Java

Source: Internet
Author: User

Java object-oriented language is widely known. Java is a pure object-oriented programming language, and this idea goes deep into all aspects of Java. "Everything is an object". For example, the bytecode file of each Class is represented by the Class. All fields are represented by the Field Class, and the Method is represented by the Method. Since it is an object-oriented idea, some object operation methods are provided for these classes. This is also necessary to understand reflection technology. Application background of reflection technology: For a developed program (desktop program or open-source framework), if the source code of the program is not modified, to allow users or other developers to add features, using reflection technology will be a good choice. Class is the cornerstone of reflection technology-all reflection is built on the Class. When the Java virtual machine is running, it maintains a type label called runtime for all objects. Virtual opportunities use these labels to track the "footprint" of objects ". Class is used to access and save the information. There are three methods to obtain the Class. Sample Code:

Package com. reflect. demo; public class ReflectDemo {/** the Java reflection mechanism is in the running state. For any class (class file ), all attributes and methods of this class are available. **/public static void main (String [] args) {System. out. println (createClassDemo_3 (). getName ();} // use the getClass method of the Object Class to obtain public static Class createClassDemo_1 () {Person p = new Person (); Class clazz = p. getClass (); return clazz;} // use attributes. the Class obtains public static Class createClassDemo_2 () {Class clazz = Person. class; return clazz;} public static Class createClassDemo_3 () {String className = "com. reflect. demo. person "; Class clazz = null; try {clazz = Class. forName (className);} catch (ClassNotFoundException e) {e. printStackTrace () ;}return clazz ;}}

The corresponding Person class code is as follows:
package com.reflect.demo;public class Person {private int age;private String name;public int getAge() {return age;}public void setAge(int age) {this.age = age;}public String getName() {return name;}public void setName(String name) {this.name = name;}public Person(int age, String name) {super();this.age = age;this.name = name;System.out.println("Person param run");}public Person() {super();System.out.println("Person run");}public void show(){System.out.println(name+"...show run..."+age);}private void method(){System.out.println("method run");}public void paramMethod(String str,int num){System.out.println("paramMethod run"+str+":"+num);}public static void staticMethod(){System.out.println("staticMethod run...");}}



The Constructor Class represents the Constructor Class construction method. A Constructor object is obtained based on the Class object to obtain the Constructor Class Construction Method (without parameters and parameters ). The Constructor class provides a series of methods to operate each object in Constructor. For example, you can extract comments and extract exceptions. The code example of the Constructor class is as follows:
Package com. reflect. demo; import java. lang. reflect. constructor; public class ReflectDemo2 {public static void main (String [] args) {constructorDemo_2 () ;}// get the public static void constructorDemo_1 () constructorDemo_1 () without parameters () {String className = "com. reflect. demo. person "; try {Class clazz = Class. forName (className); Constructor cons = clazz. getConstructor (); Person p = (Person) cons. newInstance ();} catch (Exception e) {e. printStackTrace () ; }}// Get the constructor with parameters. Public static void constructorDemo_2 () {String className = "com. reflect. demo. person "; try {Class clazz = Class. forName (className); Constructor cons = clazz. getConstructor (int. class, String. class); Person p = (Person) cons. newInstance (21, "zhangsan"); System. out. println (p. getAge ();} catch (Exception e) {e. printStackTrace ();}}}


The Field class represents a Field in a class. This field can be common or private. In the face of the field, we can change the value of the field, get the value of the field, get the modifier of the field, and so on.
Package com. reflect. demo; import java. lang. reflect. field; public class ReflectDemo3 {public static void main (String [] args) {fieldDemo_1 () ;}// the Filed class has two methods to obtain fields, one is to obtain all non-private fields. The other one is // to get all the fields (including private ones). However, only "tracking" is provided for the field, but this field cannot be accessed. If you want to access this field, public static void fieldDemo_1 () {String className = "com. reflect. demo. person "; try {Class clazz = Class. forName (className); Field f = clazz. getDeclaredField ("age"); Person p = (Person) clazz. newInstance (); f. setAccessible (true); // brute-force cracking, so that the virtual machine does not check the security of this field f. set (p, 22); // modify the field value corresponding to the object. Int age = f. getInt (p); // access field System. out. println (age);} catch (Exception e) {e. printStackTrace ();}}}



The Method class is the representation of methods in the Java class. Like above, this class provides a series of methods-related objects, such as return values, parameters (both constructor methods and methods). This class can also be used to call methods represented by this object. Sample Code:
Package com. reflect. demo; import java. lang. reflect. Constructor; import java. lang. reflect. Method;/** get methods in the specified class. **/Public class ReflectDemo4 {public static void main (String [] args) {methodDemo_2 () ;}// get the method without parameters and call back the method represented by this object. Public static void methodDemo_1 () {String className = "com. reflect. demo. person "; try {Class clazz = Class. forName (className); Method m = clazz. getMethod ("show", null); Person p = (Person) clazz. newInstance (); m. invoke (p, null);} catch (Exception e) {e. printStackTrace () ;}} public static void methodDemo_2 () {String className = "com. reflect. demo. person "; try {Class clazz = Class. forName (className); Method m = clazz. getMethod ("paramMethod", String. class, int. class); Person p = (Person) clazz. newInstance (); m. invoke (p, "wangwu", 22);} catch (Exception e) {e. printStackTrace ();}}}





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.