The name reflection is used to describe code which is able to inspect other code in the same system (or itself).
(名称反射用于描述能够检查同一系统(或本身)中其他代码的代码。)
For example, say you have an object of an unknown type in Java, and you would like to call a 'doSomething' method on it if one exists.
(例如,假设您在Java中有一个未知类型的对象,并且您想在该对象上调用“ doSomething”方法(如果存在)。)
Java's static typing system isn't really designed to support this unless the object conforms to a known interface, but using reflection, your code can look at the object and find out if it has a method called 'doSomething' and then call it if you want to. (除非对象符合已知的接口,否则Java的静态类型化系统并不是真正为支持该类型而设计的,但是使用反射,您的代码可以查看该对象并确定其是否具有名为“ doSomething”的方法,然后在需要时调用该方法。想要。)
So, to give you a code example of this in Java (imagine the object in question is foo) :
(因此,为您提供一个Java代码示例(假设有问题的对象是foo):)
Method method = foo.getClass().getMethod("doSomething", null);
method.invoke(foo, null);
One very common use case in Java is the usage with annotations.
(Java中一种非常常见的用例是带注释的用法。)
JUnit 4, for example, will use reflection to look through your classes for methods tagged with the @Test annotation, and will then call them when running the unit test. (例如,JUnit 4将使用反射来遍历类,以查找带有@Test批注的方法,然后在运行单元测试时调用它们。)
There are some good reflection examples to get you started at http://docs.oracle.com/javase/tutorial/reflect/index.html
(有一些不错的反思示例,可帮助您入门: http://docs.oracle.com/javase/tutorial/reflect/index.html)
And finally, yes, the concepts are pretty much similar in other statically types languages which support reflection (like C#).
(最后,是的,在支持反射的其他静态类型语言(如C#)中,这些概念非常相似。)
In dynamically typed languages, the use case described above is less necessary (since the compiler will allow any method to be called on any object, failing at runtime if it does not exist), but the second case of looking for methods which are marked or work in a certain way is still common. (在动态类型的语言中,上述用例不是必需的(因为编译器将允许在任何对象上调用任何方法,如果不存在则在运行时失败),但是第二种情况是查找标记或以某种方式工作仍然很普遍。)
Update from a comment:
(来自评论的更新:)
The ability to inspect the code in the system and see object types is not reflection, but rather Type Introspection.
(检查系统中的代码并查看对象类型的能力不是反射,而是类型自省。)
Reflection is then the ability to make modifications at runtime by making use of introspection. (然后,反射就是利用自省功能在运行时进行修改的能力。)
The distinction is necessary here as some languages support introspection, but do not support reflection. (此处的区别是必要的,因为某些语言支持自省,但不支持反射。)
One such example is C++ (C ++就是一个这样的例子。)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…