cool hit counter Zero coupling of code and infinite extension of functionality using JAVA reflection techniques!_Intefrankly

Zero coupling of code and infinite extension of functionality using JAVA reflection techniques!


1. Background on the use of reflection

   Recently, I have been working on a feature that implements the email sending function, but the email sending has different content and data formats, and at the beginning of the design, the sending content was written directly in the sending module, and then I found that after the feature was added, I could not continue to write in it, because the function was fixed, so I had to add a new sending module, which is equivalent to maintaining two sets of code, the sending function and the sending format configuration code coupling is too serious, I have been thinking about refactoring this feature, and then I had time to start thinking about refactoring.

   I have been thinking about my send function is fixed, how to send different content and format to extract it, later add new content, just write the style and format of the class, the send module will automatically match the content to be sent it; at first thought of using polymorphism, the parent class to call the function of the child class, but found a problem, is that each time you call the need to create objects through Fu f = new Zi() this pattern, but in the send module can not determine which subclass to use to create, without changing the code can not do new Zi() dynamic;.

  Later quite, if I send a different function each time, you can read the configuration file to determine which class to use to call, and then send the content and format of this class, then suddenly thought of using reflection technology, in the send module I write into reflection mode, reflection of the call by reading the configuration file to determine the class and method to be called, each time a new function is added, I just set the configuration file, then the reflection of the code can be more configuration to use the class, and then call its methods, completely separate the send module and content format, do not need to maintain the send module again. nice!!!

Reflection is one of the key techniques to implement the major frameworks!

2. Description of the process

From the diagram, we can see that the reflection place can be automatically implemented according to the configuration file to call different functions, so that in the future when we add new functions, we only need to write the corresponding class and the corresponding configuration file, then the new code will be automatically called.

3. Principle of reflection technology

3.1、Way to get class Generic way

Class car = Class.forName("com.gxy.src.Car"); //Note that this string must be the real path, It's the class path with the package name, bag name. class name

3.2、Get the constructor of class

1.Get the construction method.

1).Bulk approach. public Constructor[] getConstructors(): all" communal" Construction method public Constructor[] getDeclaredConstructors(): Get all constructor methods( Including private、 protected、 default、 publicly owned)

Constructor[] con =car .getDeclaredConstructors(); 2).Get a single method and call. public Constructor getConstructor(Class... parameterTypes): Get a single" communal" Construction method: public Constructor getDeclaredConstructor(Class... parameterTypes): gain" A constructor method" Can be private, or protected、 default、 publicly owned; Constructor con = clazz.getConstructor(null);

Constructor con = clazz.getConstructor(Char.class);

Calling the constructor method.

Constructor-->newInstance(Object... initargs)

  Object obj = con.newInstance();

  Object obj = con.newInstance('r');

2、newInstance beConstructor Methods of the class( Classes that manage constructors)

The api is explained as.

newInstance(Object... initargs) using thisConstructor object representation of the constructor to create a new instance of the declared class of that constructor and initialize that instance with the specified initialization parameters.

Its return value is of type T, so newInstance is a new instance object of the declared class that creates a constructor method. and call for it

3.3, the method to get the class Look through the code

 // Get all the methods in the class.
        public static void method_1() throws Exception {
            Class clazz = Class.forName("com.makaruina.reflect.Person");
             // Gets all the public methods in the class, including inherited and implemented methods.
            Method[] methods = clazz.getMethods();
// Gets all the methods in the class, including private methods, but not inherited methods.
            methods = clazz.getDeclaredMethods();
            for(Method method : methods) {
                System.out.println(method);
            }
        }
         // Get the specified method.
        public static void method_2() throws Exception {
            Class clazz = Class.forName("com.makaruina.reflect.Person");
             // Get the method with the specified name.
            Method method = clazz.getMethod("show", int.class,String.class);
             // To run the specified method, of course the method object knows best, and in order for the method to run, it is sufficient to call the method object's invoke method, but the method run must be explicit about the object it belongs to and the specific actual parameters.
            Object obj = clazz.newInstance();
            method.invoke(obj, 39,"hehehe");// Execute a method
        }
         // Want to run private methods.
        public static void method_3() throws Exception {
            Class clazz = Class.forName("com.makaruina.reflect.Person");
             // Want to get private methods. Must use getDeclearMethod();
            Method method = clazz.getDeclaredMethod("method", null);
             // Private methods cannot be accessed directly because of insufficient permissions. Access is non-essential and can be done by violence.
             method.setAccessible(true);// Generally rarely used, as private is hidden, so try not to access it.
        }
         // Reflected static methods.
        public static void method_4() throws Exception {
            Class clazz = Class.forName("com.makaruina.reflect.Person");
            Method method = clazz.getMethod("function",null);
            method.invoke(null,null);
        }

3.3、Get the properties of class By code

 * Gets the member variable and calls.
 * 
  * 1. Bulk
 *         1).Field[] getFields(): Get all the" public field"
  *         2). Field[] getDeclaredFields(): gets all fields, including: private, protected, default, public.
  * 2. To obtain a single.
 *         1).public Field getField(String fieldName): Get a certain" communal" (numeric, data) field;
  *         2). public Field getDeclaredField(String fieldName): get a field (can be private)
 * 
  *      Set the value of the field.
 *         Field --> public void set(Object obj,Object value):
  *                     Parameter Description.
  *                     1. obj: the object in which the field to be set is located.
  *                     2. value: the value to be set for the field.

3.4. Get the main method Look through the code

try {
             //1. Get the bytecode of the Student object
            Class clazz = Class.forName("fanshe.main.Student");
            
             //2. Get the main method
             Method methodMain = clazz.getMethod("main", String[].class);// The first parameter: Method name, The second parameter: Types of method formal parameters,
             //3. Calling the main method
            // methodMain.invoke(null, new String[]{"a","b","c"});
              // the first parameter, object type, because the method is static, so null can be, the second parameter is an array of String, here to note that in jdk1.4 is an array, jdk1.5 is variable parameters after
             // Here the demolition will  new String[]{"a","b","c"}  break up into3 subject。。。 So it needs to be turned strong。
             methodMain.invoke(null, (Object)new String[]{"a","b","c"});// Way I
            // methodMain.invoke(null, new Object[]{new String[]{"a","b","c"}});// Mode 2
            
        } catch (Exception e) {
            e.printStackTrace();
        }

4. Reflection allows you to cross over the generalization check

Why generic types can go beyond generic checks --- Generics are used at compile time, and are erased (automatically invalidated) after compilation.

Examples.

ArrayList<String> strList = new ArrayList<>();
        strList.add("aaa");
        strList.add("bbb");
        
    //    strList.add(100);
         // Get the Class object of the ArrayList and call the add() method in reverse to add the data
         Class listClass = strList.getClass();  // get the bytecode of the strList object object
         //Get the add() method
        Method m = listClass.getMethod("add", Object.class);
         // call the add() method
        m.invoke(strList, 100);
        
         // traversing the set
        for(Object obj : strList){
            System.out.println(obj);
        }

Recommended>>
1、That day I was killed by the ai
2、Qts Remove specified startend of line characters
3、Bitcoins biggest drop
4、Who am I beside you and me
5、Sneak peek Your life is being changed by the sharing chain

    已推荐到看一看 和朋友分享想法
    最多200字,当前共 发送

    已发送

    朋友将在看一看看到

    确定
    分享你的想法...
    取消

    分享想法到看一看

    确定
    最多200字,当前共

    发送中

    网络异常,请稍后重试

    微信扫一扫
    关注该公众号