JAVA learning lesson 64th-reflection mechanism

Source: Internet
Author: User

JAVA learning lesson 64th-reflection mechanism

The Java reflection mechanism is in the running state. For any class, all attributes and methods of this class can be known,Any method and attribute of an object can be called. This dynamically obtained information and the function of dynamically calling the object method is called the reflection mechanism of java language. To put it simply: it can dynamically obtain information in the class (all in the class), which is the reflection of java. It can also be understood as an anatomy of the class.

Basic application scenarios of reflection mechanisms:

For example, an application (TomCat) of a program exposes an interface to improve its scalability, and defines a class to implement this interface externally, but cannot create new objects within the application, therefore, the application will provide a configuration file. You can use the interface to write the written class name that implements the interface into the configuration file, the application uses the reflection mechanism to obtain the bytecode file of the class with the specified name and load the content to call the file. This is the basic application of the reflection mechanism.

Conclusion: The reflection technology improves the scalability of the program, and the application is simple. The bridge between the user and the program is changed to the configuration file.

To dissect a class file, you only need to obtain the bytecode file of the class.

In reality, Things constantly extract their common content to get classes to describe things. In the reflection mechanism, bytecode is also extracted upwards and Class is used to describe bytecode files, then, you can generate an object and provide a method to obtain the members of the bytecode file, such as the name, field, constructor, and general function. Reflection is based on this class.

Define demo class

public class Man {private int age;private String name;public Man() {super();System.out.println("Man run");}public Man(int age, String name) {super();this.age = age;this.name = name;System.out.println("Man run yes"+this.name+this.age);}public void show(){System.out.println(age+"..show.."+name);}private void privatemethod(){System.out.println(age+"..method.."+name);}public void print(int num,String line){System.out.println(num+"..print.."+line);}public static void staticmethod(){System.out.println("..staticmethod..");}}

How to obtain Class objects

To dissect a bytecode file, you must obtain the object of the bytecode file.

There are three methods to obtain bytecode file objects:

1. The getClass method in the Object class
In this way, you must specify a specific class and create an object.

public static void get_Class_Object() {Man man1 = new Man();    Class
  clas1 = man1.getClass();    Man man2 = new Man();    Class
  clas2 = man2.getClass();        System.out.println(clas1==clas2);}

2. Any data type has a static attribute. class to obtain its corresponding Class Object
Relatively simple, but it is still necessary to clarify the static members in the class, and the scalability is not high

public static void get_Class_static() {Class
  cls1 = Man.class;Class
  cls2 = Man.class;System.out.println(cls1==cls2);}

3. You can obtain the class by using the string name of the given class (important)
You can use methods in the Class to complete

This method is forName (); this method only requires a name.

API:forName(String className)
ReturnsClassObject.

API:forName(String name, boolean initialize,ClassLoader loader)
Returns the class or interface associated with the given string name using the given class loader.ClassObject.

Public static void get_Class () throws ClassNotFoundException {// G: \ java \ fan \ bin \ fan \ Man. class // The default classpath path is src, binString classname = "fan. man "; // specify the Class in the package
 Cls = Class. forName (classname); System. out. println (cls );}
Note that an exception is thrown.

Obtain the constructor in the Class.

Man man = new Man (); in the past, the new object first looks for the bytecode file of the Class Based on the name of the new class and loads it into the memory, create the bytecode file object, and then create the Man object corresponding to the bytecode file.

API:newInstance()

Create thisClassA new instance of the class represented by the object. It is similar to usingnewThis class is instantiated by expression. If the class has not been initialized, initialize the class.

It is actually the constructor of the null parameter in Man.

Empty parameter constructor in Man class

Public static void reflect_Demo () throws ClassNotFoundException, InstantiationException, IllegalAccessException {String classname = "fan. Man"; // find the Class name file and load it into the memory to generate the Class Object Class
 Cls = Class. forName (classname); Object obj = cls. newInstance ();}

There is no null parameter constructor in the Man class.

Man man = new Man (11, "");

If you call the preceding method directly, the initialization exception InstantiationException is thrown.

If there is an empty parameter constructor, but it is a private Man (){},Will throw invalid access exception IllegalAccessException

Therefore, when you get the object embodied in the specified name class, and object initialization does not use a null parameter to construct, you should first obtain its constructor, which can be completed through the bytecode file object, getConstructor

API:getConstructor(Class ... parameterTypes)
ReturnsConstructorObject, which reflectsClassSpecifies the public constructor of the class represented by the object.

API:getDeclaredConstructors()
ReturnConstructorAn array of objects, which reflectClassAll constructor methods of the class declaration represented by the object.

WhileThe Constructor object contains the method new object.

API:newInstance(Object... initargs)
Use thisConstructorObject To create a new instance of the Declaration class of the constructor, and initialize the instance with the specified initialization parameters.

Public static void reflect_Demo () throws Exception {String classname = "fan. Man"; Class
 Cls = Class. forName (classname); // parameter array. the bytecode corresponding to an int basic data type is int. classConstructor.
 Constructor = cls. getConstructor (int. class, String. class); // obtains the Object obj = constructor. newInstance (11, "a") of the specified constructor ");}

However, when configuring the file, you must specify the parameter information of the Class Name and constructor.

PS: Generally, the reflected classes contain null parameters, because it is convenient to obtain instances.

Obtain fields in the Class

API:getField(String name)
ReturnsFieldObject, which reflectsClassThe specified public member field of the class or interface represented by the object.

API:getFields()
ReturnsFieldArray of objects, which reflectClassAll accessible public fields of the class or interface represented by the object.

API:getDeclaredField(String name)
ReturnsFieldObject, which reflectsClassThe specified declared field of the class or interface represented by the object.

API:getDeclaredFields()
ReturnFieldAn array of objects, which reflectClassAll fields declared by the class or interface indicated by the object.

Public static void reflect_Demo () throws Exception {String classname = "fan. Man"; Class
 Cls = Class. forName (classname); Object object = cls. newInstance (); // Field field = cls. getField ("name"); // contains the age and name fields. Only public Field = cls can be obtained. getDeclaredField ("name"); // only this class can be obtained, including private System. out. println (field); // obtain the field value ......... // Object obj = field. get (object); // System. out. println (obj); // The Reverse query fails because it is private. // The ACL check for private fields is canceled.-> brute force access to field. setAccessible (true); // The Field's parent class method, modifying its access permission field. set (object, "a"); // sets the Object obj = field. get (object); System. out. println (obj );//}

API: The AccessibleObject class is the base class of the Field, Method, and Constructor object. It provides the ability to mark reflected objects as canceling the default Java language access control check during use.

PS: it is not recommended to access data through brute force access.

Obtain methods in a specified Class

Obtain a method without Parameters

Public static void reflect_Demo () throws Exception {String classname = "fan. Man"; Class
 Cls = Class. forName (classname); // Method [] methods = cls. getMethods (); // obtain all public methods of the class and its parent class. // methods = cls. getDeclaredMethods (); // only obtain all methods in this class, including private // for (Method M: methods) {// System. out. println (M); // Method = cls for a non-argument method. getMethod ("show", null); // note that unlike the constructor, the method name and method parameter list // Object obj = cls. newInstance (); // No parameter construction // method. invoke (obj, null); Constructor
 Constructor = cls. getConstructor (int. class, String. class); Object obj = constructor. newInstance (1, "a"); // method with parameters. invoke (obj, null); // call the underlying Method represented by this Method object for the specified object with the specified parameter .}

Get the method with Parameters

Public static void reflect_Demo () throws Exception {String classname = "fan. Man"; Class
 Cls = Class. forName (classname); Method method = cls. getMethod ("print", int. class, String. class); // method parameter list Object obj = cls. newInstance (); method. invoke (obj, 11, "a"); // call the obtained method}


Reflection exercise:

Public class Computer {public void run () {System. out. println ("Computer is run .... ");} public void UseInter (Inter p) {// exposes the interface to improve the scalability of if (p! = Null) {p. open (); p. close () ;}} public interface Inter {public void open (); public void close ();} public class NetCard implements Inter {public void open () {System. out. println ("NetCard open .... ");} public void close () {System. out. println ("NetCard close... ") ;}} public class SoundCard implements Inter {public void open () {System. out. println ("SoundCard open... ");} public void close () {System. out. println ("SoundCard close... ") ;}} public class Main {public static void main (String [] args) throws Exception {Computer com = new Computer (); com. run (); // com. useInter (new SoundCard (); // polymorphism, but in this case, you need to modify the existing code. // use the radiation mechanism to obtain the Class file, create the object File conFile = new File ("G: \ java \ fan \ bin \ fan \ inter. properties "); Properties pro = new Properties (); FileInputStream FD = new FileInputStream (conFile); pro. load (FCM); // load the information in the stream into the set for (int x = 0; x <pro. size (); x ++) {String intername = pro. getProperty ("Inter" + (x + 1); Class
 Cls = Class. forName (intername); // use Class to load this Inter subclass Object obj = cls. newInstance (); // create Inter object Inter p = (Inter) obj; com. useInter (p);} fiis. close ();}}

Because XML has not been learned, use properties instead.



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.