What exactly is Reflection and when is it a good approach?

前端 未结 11 1671
天命终不由人
天命终不由人 2020-12-25 14:58

What exactly is Reflection? I read the Wikipedia article on this subject and I understand that it is a kind of meta-programming, where the program can modify itself at run-

11条回答
  •  感情败类
    2020-12-25 15:16

    The first good example I can think of off the top of my head is for when you need to execute a set of methods on a given object without knowing at compile-time what methods will exist in it.

    Take unit testing frameworks for example. The test runner class that is responsible for running all your unit tests doesn't know ahead of time what you are going to name your methods. All it knows is that they will be prefixed with "test" (or in Java 5's case, annotated with @Test). So when given a test class, it reflects on that class in order to get a list of all the methods in it. Then, it iterates through those method names as strings and calls those methods on the object if they start with "test". That wouldn't be possible without reflection. And that's just one example.

提交回复
热议问题