What is reflection and why is it useful?

前端 未结 21 2879
春和景丽
春和景丽 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);
        }
    
    }
    

提交回复
热议问题