理解Java中的Object Reflection优势(Understanding an Object Reflection advantage in Java)

编程入门 行业动态 更新时间:2024-10-24 07:22:32
理解Java中的Object Reflection优势(Understanding an Object Reflection advantage in Java)

我正在学习Java中的Object Reflection并阅读它提供的以下优势(来自Cracking the Coding Interview,Laakmann McDowell):

当我们事先不知道方法时,我们可以通过名称调用方法。 例如,我们可以让用户传入类名,构造函数的参数和方法名。 然后,我们可以使用此信息来创建对象并调用方法。 如果没有反思,做这些操作将需要一系列复杂的if语句,如果可能的话

我很难理解这一点:如果我们知道方法名称,我们不能只是调用它吗?

I am learning about Object Reflection in Java and read the following advantage it offers (From Cracking the Coding Interview, Laakmann McDowell):

We can call methods by name, when we don't know the method in advance. For example, we may let the user pass in a class name, parameters for the constructor, and a method name. We can then use this information to create an object and call a method. Doing these operations without reflection would require a complex series of if-statements, if it's possible at all

I have trouble understanding this point: If we know the method name, can't we just call it anyway?

最满意答案

这意味着反射API允许您在运行时通过它的名称调用方法。 如果在编译时不知道要调用的方法的名称,这将非常有用。

例如,假设您创建了某种小型脚本语言,您希望快速调用Java代码中存在的各种方法,您可以在运行时加载这些脚本文件。 您可以获取构成脚本文件中名称的字节并调用该方法。

It means that the reflection API allows you to call a method by it's name at runtime. This would be useful if you don't know the name of the method you want to call when you compile.

For example, say you made some sort of small scripting language that you want to quickly call various methods that exist in your Java code in which you load these scripting files in at run time. You could grab the bytes that make up the name in the scripting file and call the method.

更多推荐

本文发布于:2023-07-29 18:28:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1318630.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:优势   Object   Java   Reflection   advantage

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!