Java BASICS (13) reflection and java basics reflection

Source: Internet
Author: User

Java BASICS (13) reflection and java basics reflection
I. Reflection 1. Reflection Concept

The JAVA reflection mechanism is in the running state. For any class, all attributes and methods of this class can be known. For any object, can call any of its methods and attributes. This kind of information obtained dynamically and the function of dynamically calling methods of objects is called the reflection mechanism of java language.

To dissect a class, you must first obtain the bytecode object of the class. Anatomy uses methods in the Class. Therefore, you must first obtain the Class objects corresponding to each bytecode file.

2. Main use of the Java reflection mechanism

1. Determine the class to which any object belongs during running.

2. Construct the object of any class at runtime.

3. Determine the member variables and methods of any class at runtime.

4. Call the methods of any object at runtime.

3. Three Methods for getting Class instance objects

1. Person p = new Person ();

Class c = p. getClass ();

For known Class objects, use the getClass () method to obtain Class instance objects.

2. Class c2 = Person. class;

Any data type has a class static member variable, which seems easier than the first method.

3. Pass the Class name as a string to the static method forName in the Class.

Class c3 = Class. forName ("Person ");

1 import com. reflect. pojo. product; 2 import org. junit. test; 3 4/** 5 * @ author zt1994 2018/3/5 6 */7 public class TestReflect {8 9/** 10 * test three methods for getting Class objects 11 * @ throws Exception12 * /13 @ Test14 public void testGetClass () throws Exception {15 // three methods of Instantiation Class any object is a Class instance 16 // The first object name. getClass () 17 Product product = new Product (); 18 Class <? Extends Product> aClass1 = product. getClass (); 19 System. out. println (aClass1); // class com. reflect. pojo. product20 // type 2. class21 Class <Product> aClass2 = Product. class; 22 System. out. println (aClass2); 23 // static Class in the third Class <?> ForName (String className) className is a Class or interface permission named 24 Class <?> AClass3 = Class. forName ("com. reflect. pojo. product "); 25 System. out. println (aClass3); 26 // compare 27 System. out. println (aClass1 = aClass2); // true28 System. out. println (aClass1 = aClass3); // true29 System. out. println (aClass2 = aClass3); // true30} 31}
4. Functions of reflection

1. increase the flexibility of the program and avoid writing the program into the code (remove the hard coding problem );

2. The reflection mechanism of Java knows the basic structure of the class and can dynamically obtain the structure of the class;

3. programmers can write their own code without knowing what classes other programmers will have;

4. Advantages of reflection: flexible and powerful (private... can be obtained ....);

5. disadvantages of reflection: Damage encapsulation and affect performance;

5. Reflection application (Common APIs) 1. Obtain the constructor

GetConstructors cannot obtain private constructor methods.

GetDeclaredConstructors can obtain all constructor methods, including private ones.

Product class:

 1 public class Product { 2     private Integer id; 3     private String productName; 4     private Integer classifyId; 5     private String brand; 6  7     public Integer getId() { 8         return id; 9     }10 11     public void setId(Integer id) {12         this.id = id;13     }14 15     public String getProductName() {16         return productName;17     }18 19     public void setProductName(String productName) {20         this.productName = productName;21     }22 23     public Integer getClassifyId() {24         return classifyId;25     }26 27     public void setClassifyId(Integer classifyId) {28         this.classifyId = classifyId;29     }30     31     public String getBrand() {32         return brand;33     }34 35     public void setBrand(String brand) {36         this.brand = brand;37     }38 }

Obtain the constructor:

1/** 2 * Test to obtain the constructor 3 */4 @ Test 5 public void testGetConstructor () throws ClassNotFoundException {6 Class <?> AClass = Class. forName ("com. reflect. pojo. Product"); 7 // get Constructor 8 <?> [] DeclaredConstructors = aClass. getDeclaredConstructors (); 9 for (Constructor <?> DeclaredConstructor: declaredConstructors) {10 System. out. println ("declaredConstructor: [" + declaredConstructor + "]"); 11} 12}
2. Create an object through reflection

1. newInstance ()

Note: You can only call a constructor without parameters. A constructor without parameters must have the permission to be accessed.

2. After obtaining the constructor object, create the object through the constructor.

1/** 2 * Test two methods for creating reflection objects 3 */4 @ Test 5 public void testCreateInstance () throws Exception {6 // method 1 Class has the corresponding method newInstance () 7 Class <?> AClass = Class. forName ("com. reflect. pojo. product "); 8 Product product = (Product) aClass. newInstance (); 9 10 // method 2 after obtaining the Constructor object, use the Constructor to create the object 11 Constructor <?> Constructor = aClass. getDeclaredConstructor (); 12 Product product1 = (Product) constructor. newInstance (); 13}
3. Obtain Methods

1. Get all methods

GetMethods

GetDeclaredMethods

2. Obtain a single method

GetMethod

GetDeclaredMethod

1/** 2 * Test obtaining method 3 */4 @ Test 5 public void testGetMethods () throws Exception {6 Class <?> AClass = Class. forName ("com. reflect. pojo. product "); 7 8 // obtain Method 9 Method [] declaredMethods = aClass. getDeclaredMethods (); 10 for (int I = 0; I <declaredMethods. length; I ++) {11 Method declaredMethod = declaredMethods [I]; 12 // get Method return type 13 Class <?> ReturnType = declaredMethod. getReturnType (); 14 // output method return type 15 System. out. println ("returnType: [" + returnType + "]"); 16 // obtain method parameter type 17 Class <?> [] ParameterTypes = declaredMethod. getParameterTypes (); 18 for (Class parameterType: parameterTypes) {19 System. out. println ("parameterType: [" + parameterType + "]"); 20} 21 // output variable name 22 System. out. println ("I:" + I + "declaredMethod: [" + declaredMethod. getName () + "]"); 23} 24}
4. Obtain fields (member variables)

1. Get all fields

GetFields, getDeclaredFields

2. Obtain a single Field

GetField, getDeclaredField

3. Modify and obtain the field value

Set (Object obj, Object value); set the Field represented by this Field Object on the specified Object variable to the specified new value.

Get (Object obj); returns the value of the Field represented by this Field on the specified Object (input obj.

1/** 2 * Get field 3 */4 @ Test 5 public void testAPI () throws ClassNotFoundException {6 // get field 7 Class <?> AClass = Class. forName ("com. reflect. pojo. product "); 8 // obtain Field 9 Field [] declaredFields = aClass. getDeclaredFields (); 10 for (Field df: declaredFields) {11 // obtain Field type 12 Class <?> Type = df. getType (); 13 System. out. println ("type: [" + type + "]"); 14 System. out. println (df); 15} 16}
5. Call the method through reflection

1. Obtain the Class instance corresponding to the Class;

2. Get the specified method in the class through reflection

3. Call methods through reflection (Method class)

Method:

Object invoke (Object obj, Object... args)

Obj: The called object.

Args: method parameters

1/** 2 * reflection call method 3 */4 @ Test 5 public void testInvoke () throws Exception {6 Product product = new Product (); 7 product. setId (7); 8 product. setClassifyId (3); 9 product. setBrand ("Lenovo"); 10 product. setProductName ("G480 notebook"); 11 12 // 1. get bytecode 13 Class <?> AClass = product. getClass (); 14 // 2. get attribute 15 Field [] declaredFields = aClass. getDeclaredFields (); 16 // 3. get attribute array 17 for (Field declaredField: declaredFields) {18 // get attribute name 19 String fieldName = declaredField. getName (); 20 // return to the get method String name 21 String methodName = "get" + toMethodName (fieldName ); 22 // obtain the Method object by using the method name reflection 23 Method method = aClass. getMethod (methodName); 24 // execution method 25 Object invoke = method. invoke (product); 26 // replace String type 27 String s = String. valueOf (invoke); 28 System. out. println (fieldName + "=" + s); 29} 30}

 

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.