撒拉嘿哟木头 2008-09-01 08:39 采纳率: 100%
浏览 279
已采纳

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

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.

转载于:https://stackoverflow.com/questions/37628/what-is-reflection-and-why-is-it-useful

  • 写回答

19条回答 默认 最新

  • 北城已荒凉 2008-09-01 08:44
    关注

    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'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.

    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);
    

    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.

    There are some good reflection examples to get you started at 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#). 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++

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(18条)

报告相同问题?

悬赏问题

  • ¥15 运筹学排序问题中的在线排序
  • ¥15 关于#flink#的问题:关于docker部署flink集成hadoop的yarn,请教个问题flink启动yarn-session.sh连不上hadoop
  • ¥30 求一段fortran代码用IVF编译运行的结果
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 lammps拉伸应力应变曲线分析
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥15 请问Lammps做复合材料拉伸模拟,应力应变曲线问题