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

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

问题描述

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

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

There are some good reflection examples to get you started at http://docs.oracle.com/javase/tutorial/reflect/index.html

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

And finally, yes, the concepts are pretty much similar in other statically types 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.

从评论中更新:


检查系统中的代码并查看对象类型的能力是
不是反射,而是Type Introspection。然后通过利用
内省来反射
在运行时进行修改的能力。这里的区别是必要的,因为一些语言
支持内省,但不支持反射。一个这样的例子
是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天全站免登陆