Reflection simple instance

First, case: payment function - > WeChat, Alipay, cloud flash payment and so on.

Provide a payment interface

package com.lmh;

/**Provide payment interface
 * @author codelmh
 * @data 2021/11/24
 */
public interface Payment {

    void payOnline();

}

  Wechat payment implements payment interface

package com.lmh;

/** Wechat realizes payment interface
 * @author codelmh
 * @data 2021/11/24
 */
public class weChat implements Payment{

    @Override
    public void payOnline() {
        System.out.println("using wechat pay");
    }
}

  Alipay implements payment interface

package com.lmh;

/** Alipay implements payment interface
 * @author codelmh
 * @data 2021/11/24
 */
public class AliPay implements Payment{

    @Override
    public void payOnline() {
        System.out.println("using AliPay to pay...");
    }
}

  Realize analog front-end payment function

package com.lmh;

/**
 * @author codelmh
 * @data 2021/11/24
 */
public class TestPayment {
    public static void main(String[] args) {
        //Payment method submitted by analog front end
        String str = "WeChat";
        if ( "WeChat".equals(str)) {
            pay(new weChat());
        }
        if ("Alipay".equals(str)) {
            pay(new AliPay());
        }
    }
    public static void pay(weChat weChat){
        weChat.payOnline();
    };
    public static void pay(AliPay aliPay){
        aliPay.payOnline();
    }
}

  Suppose we add cloud flash payment and various bank card payments. For each payment method, we need to add an additional method to our TestPayment. If there are 100, we need to write 100 pay methods. Low scalability

So we have a solution: polymorphism, so that we can use one method to call multiple implementation classes

package com.lmh;

/**
 * @author codelmh
 * @data 2021/11/24
 */
public class TestPayment {
    public static void main(String[] args) {
        //Payment method submitted by analog front end
        String str = "WeChat";
        if ("WeChat".equals(str)) {
            pay(new weChat());
        }
        if ("Alipay".equals(str)) {
            pay(new AliPay());
        }
    }

    //Use polymorphism
    public static void pay(Payment payment) {
        payment.payOnline();
    }
}

The extensibility of this code has indeed improved a lot, but it has not reached the best. The above branches still need to be added or deleted manually, so we have a reflection mechanism.

package com.lmh;

import java.lang.reflect.Method;

/**
 * @author codelmh
 * @data 2021/11/24
 */
public class RefelctPayment {

    public static void main(String[] args) throws Exception {
        //Analog front end value transmission
        String str = "com.lmh.AliPay";
        // Use class. Forname (class fully qualified name) to get the object
        Class<?> clazz = Class.forName(str);
        // Object instantiation
        Object o = clazz.newInstance();
        // Get payOnline method of object
        Method pay = clazz.getMethod("payOnline");
        // method of calling object
        pay.invoke(o);
    }
}

It can be found that just four lines of code will make the code very extensible, which is reflection

2, What is reflection

         Java's reflection mechanism means that in the running state of the program, you can construct the object of any class, understand the class to which any object belongs, understand the member variables and methods of any class, and call the properties and methods of any object. This function of dynamically obtaining program information and dynamically calling objects is called the reflection mechanism of Java language. Reflection is regarded as the key to dynamic language.

3, Application scenario of reflection

        Through the above case, we should understand that reflection is generally used in places with high code generality or framework writing.

4, The concept of reflection

Why is it called reflection in java? (own understanding)

java has the feature of encapsulation, so if we compare the encapsulation class to a room without any exit, we can't get anything from this room. java reflection mechanism is to press a door in the room, and then get everything in the room.

Question: will the encapsulation of java be destroyed

         First, encapsulation is to hide the specific implementation details and provide the functions as a whole to the external use of the class, that is, public methods can complete the functions of the class. When others use this class, if private methods are called directly through reflection, the function of the class may not be realized at all, and even errors may occur. Therefore, calling private methods through reflection can be said to be of no use, and developers do not need to deliberately destroy the encapsulated class. From this point of view, encapsulation has not been destroyed. (excerpt from Baidu Q & A)

Tags: Java reflection

Posted on Wed, 24 Nov 2021 02:43:11 -0500 by jdubwelch