What is reflection and why is it useful?

前端 未结 21 2800
春和景丽
春和景丽 2020-11-21 04:36

What is reflection, and why is it useful?

I\'m particularly interested in Java, but I assume the principles are the same in any language.

相关标签:
21条回答
  • 2020-11-21 05:04

    Simple example for reflection. In a chess game, you do not know what will be moved by the user at run time. reflection can be used to call methods which are already implemented at run time:

    public class Test {
    
        public void firstMoveChoice(){
            System.out.println("First Move");
        } 
        public void secondMOveChoice(){
            System.out.println("Second Move");
        }
        public void thirdMoveChoice(){
            System.out.println("Third Move");
        }
    
        public static void main(String[] args) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException { 
            Test test = new Test();
            Method[] method = test.getClass().getMethods();
            //firstMoveChoice
            method[0].invoke(test, null);
            //secondMoveChoice
            method[1].invoke(test, null);
            //thirdMoveChoice
            method[2].invoke(test, null);
        }
    
    }
    
    0 讨论(0)
  • 2020-11-21 05:05

    Reflection is to let object to see their appearance. This argument seems nothing to do with reflection. In fact, this is the "self-identify" ability.

    Reflection itself is a word for such languages that lack the capability of self-knowledge and self-sensing as Java and C#. Because they do not have the capability of self-knowledge, when we want to observe how it looks like, we must have another thing to reflect on how it looks like. Excellent dynamic languages such as Ruby and Python can perceive the reflection of their own without the help of other individuals. We can say that the object of Java cannot perceive how it looks like without a mirror, which is an object of the reflection class, but an object in Python can perceive it without a mirror. So that's why we need reflection in Java.

    0 讨论(0)
  • Example:

    Take for example a remote application which gives your application an object which you obtain using their API Methods . Now based on the object you might need to perform some sort of computation .

    The provider guarantees that object can be of 3 types and we need to perform computation based on what type of object .

    So we might implement in 3 classes each containing a different logic .Obviously the object information is available in runtime so you cannot statically code to perform computation hence reflection is used to instantiate the object of the class that you require to perform the computation based on the object received from the provider .

    0 讨论(0)
提交回复
热议问题