Java Study Notes 54 (reflection details) and java Study Notes 54

Source: Internet
Author: User

Java Study Notes 54 (reflection details) and java Study Notes 54

Reflection concept:

The java reflection mechanism is in the running state. All attributes and methods can be known for any class.

Any method and attribute of an object can be called. This dynamic acquisition and calling function is called the reflection mechanism of java.

 

Actual purpose:

A java program has been completed, but if you want to add new functions, you cannot modify the source code. In this case, the reflection mechanism is used.

 

 

Three methods to obtain class files:

 

You can easily customize a Person class:

Package demo; public class Person {public String name; private int age; public Person () {} public Person (String name, int age) {this. name = name; this. age = age;} private Person (int age, String name) {this. name = name; this. age = age;} public void eat () {System. out. println ("people eat");} public void sleep (String s, int a, double d) {System. out. println ("sleeping" + s + "..... "+ a + "..... "+ d);} private void playGame () {System. out. println ("playing games");} public String toString () {return "Person [name =" + name + ", age =" + age + "]";} public String getName () {return name;} public void setName (String name) {this. name = name;} public int getAge () {return age;} public void setAge (int age) {this. age = age ;}}
View Code

Obtain the class Object of the person class (the same object is essentially obtained in three methods ):

Package demo; public class ReflectDemo {public static void main (String [] args) {// 1. object To get Person p = new Person (); Class c = p. getClass (); System. out. println (c); // 2. obtain Class c1 = Person by Class name. class; System. out. println (c1); System. out. println (c = c1); // true System. out. println (c. equals (c1); // true // only one class file exists. Both methods obtain the same object // 3. class static method. The parameter must contain the package name to prevent duplicate names. try {Class c2 = Class. forName ("demo. person "); System. out. println (c2);} catch (ClassNotFoundException e) {e. printStackTrace ();}}}

 

Method for constructing null parameters obtained by reflection:

Package demo; import java. lang. reflect. constructor; public class ReflectDemo {public static void main (String [] args) throws ClassNotFoundException {Class c = Class. forName ("demo. person "); function1 (c); function2 (c);} private static void function1 (Class c) {// get all public permissions (public) constructor [] cons = c. getConstructors (); for (Constructor con: cons) {System. out. println (con); // output: // public demo. person (java. lang. string, int) // public demo. person ()} public static void function2 (Class c) {// obtain the null parameter constrtor and execute (toString method) try {Constructor con = c. getConstructor (); Object obj = con. newInstance (); System. out. println (obj); // output: Person [name = null, age = 0]} catch (Exception ex) {ex. printStackTrace ();}}}

 

 

Construction Method for retrieving Parameters Using Reflection:

Package demo; import java. lang. reflect. constructor; public class ReflectDemo {public static void main (String [] args) throws Exception {Class c = Class. forName ("demo. person "); Constructor con = c. getConstructor (String. class, int. class); System. out. println (con); Object object = con. newInstance ("James", 20); System. out. println (object) ;}}/* output: public demo. person (java. lang. string, int) Person [name = Michael, age = 20] */

 

It is found that the amount of code in the above method is too large and the method is quicker:

Premise: the reflected class must have a null parameter constructor and the constructor permission must be public.

Package demo; public class ReflectDemo {public static void main (String [] args) throws Exception {Class c = Class. forName ("demo. person "); // method defined in the Class, T newInstance () directly creates the Object instance of the reflected Class Object obj = c. newInstance (); System. out. println (obj );}}

 

Reflection gets the private constructor method (this method is not recommended for daily development ):

Package demo; import java. lang. reflect. constructor; public class ReflectDemo {public static void main (String [] args) throws Exception {Class c = Class. forName ("demo. person "); // obtain all Constructor methods (including private ones) // Constructor [] cons = c. getDeclaredConstructors (); Constructor con = c. getDeclaredConstructor (int. class, String. class); con. setAccessible (true); // cancel the permission and destroy the encapsulation Object = con. newInstance (18, "James"); System. out. println (object); // Person [name = Zhang San, age = 18]}

 

 

Reflection gets the member variables of the class and modifies them:

Package demo; import java. lang. reflect. constructor; import java. lang. reflect. field; public class ReflectDemo {public static void main (String [] args) throws Exception {Class c = Class. forName ("demo. person "); // obtain all public member Field [] fields = c. getFields (); // obtain all the member variables Field [] fields2 = c. getDeclaredFields (); for (Field field: fields2) {System. out. println (field);} // obtain the specified member variable and modify Field field = c. getField ("name"); Object object = c. newInstance (); field. set (object, "Zhang San"); System. out. println (object); // output: Person [name = Zhang San, age = 0]}

 

 

Obtain the member method by reflection and execute:

Package demo; import java. lang. reflect. method; public class ReflectDemo {public static void main (String [] args) throws Exception {Class c1 = Class. forName ("demo. person "); // obtain all public methods/** Method [] methods = c1.getMethods (); * for (Method method: methods) {* System. out. println (method);} * // obtain the specified Method run (null parameter) method = c1.getMethod ("eat"); Object obj = c1.newInstance (); method. invoke (obj); // output: person-to-dinner // Method method1 = c1.getMethod ("sleep", String. class, int. class, double. class); Object obj1 = c1.newInstance (); method1.invoke (obj1, "break", 10, 10.11); // output: A person is sleeping and resting ..... 10 ..... 10.11 // you can use the method mentioned above to run the private method }}

 

Generic erasure of reflection:

Package demo; import java. lang. reflect. method; import java. util. arrayList; public class ReflectTest {public static void main (String [] args) throws Exception {ArrayList <String> array = new ArrayList <String> (); // The method used to add an array. add ("a"); array. add ("1"); Class class1 = array. getClass (); Method method = class1.getMethod ("add", Object. class); method. invoke (array, 100); method. invoke (array, 666.666); method. invoke (array, 0.1); System. out. println (array); // output: [a, 1,100,666.666, 0.1]}

 

Reflection is implemented through the configuration file:

Sometimes you want to change the source code, but you cannot change the source code. You can do this:

Three custom classes:

Package demo; public class Person {public void eat () {System. out. println ("eat ");}}
View Code
Package demo; public class Student {public void study () {System. out. println ("Student learning ");}}
View Code
Package demo; public class Worker {public void job () {System. out. println ("working for office workers ");}}
View Code

Configuration File: config. properties

#className=demo.Student#methodName=studyclassName=demo.PersonmethodName=eat#className=demo.Worker#methodName=job

Test class:

Package demo; import java. io. fileReader; import java. lang. reflect. method; import java. util. properties;/** call the Person method, call the Student method, and call the Worker Method * class is not clear, and the method is not clear * implement this function through the configuration file * run the class name and method name, in the form of a key-value pair, write in the text * which class to run and read the configuration file * implementation steps: * 1. prepare the configuration file, key-Value Pair * 2. IO stream read configuration file Reader * 3. the key-Value Pair stored in the Properties * set in the file is the class name and method name * 4. obtain the class Object of the specified class through reflection * 5. class Object to obtain the specified Method * 6. running Method */public class Test {public static void main (String [] args) throws Exception {// IO stream read configuration file FileReader r = new FileReader ("config. properties "); // create the set object Properties pro = new Properties (); // call the set method load to pass the stream object pro. load (r); r. close (); // obtain the value String className = pro by using the key. getProperty ("className"); String methodName = pro. getProperty ("methodName"); // obtain the class Object Class c = Class of the specified class through reflection. forName (className); Object obj = c. newInstance (); // obtain the specified Method name method = c. getMethod (methodName); method. invoke (obj );}}

 

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.