什么是反射,它为什么有用? [英] What is reflection and why is it useful?

查看:31
本文介绍了什么是反射,它为什么有用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是反射,它为什么有用?

What is reflection, and why is it useful?

我对 Java 特别感兴趣,但我认为原则在任何语言中都是相同的.

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

推荐答案

名称反射用于描述能够检查同一系统(或自身)中其他代码的代码.

The name reflection is used to describe code which is able to inspect other code in the same system (or itself).

例如,假设您在 Java 中有一个未知类型的对象,如果存在,您想对其调用doSomething"方法.Java 的静态类型系统并不是真正设计为支持这一点,除非对象符合已知接口,但是使用反射,您的代码可以查看对象并找出它是否有一个名为doSomething"的方法,然后调用它想要.

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'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 代码示例(假设有问题的对象是 foo):

So, to give you a code example of this in Java (imagine the object in question is foo) :

Method method = foo.getClass().getMethod("doSomething", null);
method.invoke(foo, null);

Java 中一个非常常见的用例是使用注解.例如,JUnit 4 将使用反射在您的类中查找带有 @Test 注释标记的方法,然后在运行单元测试时调用它们.

One very common use case in Java is the usage with annotations. 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.

http://docs 有一些很好的反射示例可以帮助您入门.oracle.com/javase/tutorial/reflect/index.html

最后,是的,这些概念在其他支持反射的静态类型语言(如 C#)中非常相似.在动态类型语言中,上面描述的用例不太必要(因为编译器将允许在任何对象上调用任何方法,如果它不存在则在运行时失败),但第二种情况是寻找标记或以某种方式工作仍然很普遍.

And finally, yes, the concepts are pretty much similar in other statically typed languages which support reflection (like 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.

评论更新:

检查系统中的代码并查看对象类型的能力是不是反射,而是类型自省.反射就是通过使用在运行时进行修改的能力内省.由于某些语言,这里有必要进行区分支持自省,但不支持反思.一个这样的例子是 C++

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++

这篇关于什么是反射,它为什么有用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆