加载中…
个人资料
前沿博客
前沿博客
  • 博客等级:
  • 博客积分:0
  • 博客访问:51,178
  • 关注人气:2
  • 获赠金笔:0支
  • 赠出金笔:0支
  • 荣誉徽章:
相关博文
推荐博文
谁看过这篇博文
加载中…
正文 字体大小:

反射编程(反思)

(2009-03-27 14:42:00)
标签:

杂谈

反射编程(反思)

Sunday, August 10th, 2008 星期日, 2008年8月10日

Incomputer science, reflection is the process by which a computer programcan observe and modify its own structure and behavior.在计算机科学,反思是指计算机程序可以观察和修改自己的结构和行为。 The programming paradigm driven by reflection is called reflective programming.编程范式的推动下反射被称为反射编程。

Inmost modern computer architectures, program instructions are stored asdata - hence the distinction between instruction and data is merely amatter of how the information is treated by the computer andprogramming language.在大多数现代计算机体系结构,程序指令存储的数据-因此区分指令和数据仅仅是一个问题是如何处理信息的计算机和编程语言。 Normally,‘instructions’ are ‘executed’ and ‘data’ is ‘processed’; however, insome languages, programs can also treat instructions as data andtherefore make reflective modifications.通常情况下, '说明'是'执行'和'数据'是'处理' ,但是,在有些语言中,程序还可以作为数据处理的指示,因此使反射的修改。 Reflectionis most commonly used in high-level virtual machine programminglanguages like Smalltalk and scripting languages, and less commonlyused in manifestly typed and/or statically typed programming languagessuch as Java and C, where it may not be possible at all.思考是最常用的高级别的虚拟机的编程语言,如Smalltalk和脚本语言,不常用的明显输入和/或静态类型编程语言,如Java和C ,它可能无法在所有。

Reflection is also known as self-modifying code, especially at the machine code and assembly language levels.反思也被称为自修改代码,特别是在机器代码和汇编语言的水平。
Reflection-Oriented Programming反射面向对象程序设计
Reflection-orientedprogramming, or reflective programming, is a functional extension tothe object-oriented programming paradigm.反思为导向的规划,或反射编程,是一个功能扩展,面向对象的编程范式。 Reflection-oriented programming includes self-examination, self-modification, and self-replication.反思为导向的编程,包括自我检查,自我改造,自我复制。 However,the emphasis of the reflection-oriented paradigm is dynamic programmodification, which can be determined and executed at runtime.然而,重点反映为导向的模式是动态的程序修改,可确定和执行在运行时。 Someimperative approaches, such as procedural and object-orientedprogramming paradigms, specify that there is an exact predeterminedsequence of operations with which to process data.一些必要的方法,如程序和面向对象的编程范式,指定有一个确切的预定序列的行动来处理数据。 Thereflection-oriented programming paradigm, however, adds that programinstructions can be modified dynamically at runtime and invoked intheir modified state.反映为导向编程范例,但补充说,程序指令可以修改运行时的动态,并援引其修改状态。 Thatis, the program architecture itself can be decided at runtime basedupon the data, services, and specific operations that are applicable atruntime.也就是说,建筑本身的程序可运行时决定的依据的数据,服务和具体的行动,均适用于在运行。

Programming sequences can be classified in one of two ways, atomic or compound.编程序列可分为以下两种方式之一,原子或化合物。 Atomic operations are those that can be viewed as completing in a single, logical step, such as the addition of two numbers.原子操作是那些可以被视为完成在一个单一的,合乎逻辑的步骤,如增加两个号码。 Compound operations are those that require a series of multiple atomic operations.复合经营是那些需要一系列的多个原子操作。

A compound statement, in classic procedural or object-oriented programming, can lose its structure once it is compiled.复合声明,在经典的程序或面向对象的程序设计,就会失去它的结构一旦汇编。 The reflective programming paradigm introduces the concept of meta-information, which keeps knowledge of program structure.反射编程范例介绍了概念的元信息,保持知识的程序结构。 Meta-informationstores information such as the name of the contained methods, the nameof the class, the name of parent classes, and/or what the compoundstatement is supposed to do.元信息存储信息,如名称所包含的方法的名称,类别,名称母公司班,和/或复合语句什么是应做的事。 Usingthis stored information, as an object is consumed (processed), it canbe reflected upon to find out the operations that it supports.使用此存储的信息,作为一个对象是消费(加工) ,它可以反映找出业务,它支持。 Theoperation that issues in the required state via the desired statetransition can be chosen at run-time without hard-coding it.的操作问题,需要国家通过的理想状态过渡可以选择在运行时没有硬编码它。

Uses利用
Reflection can be used for observing and/or modifying program execution at runtime.思考可用于观察和/或修改执行程序在运行。 Areflection-oriented program component can monitor the execution of anenclosure of code and can modify itself according to a desired goalrelated to that enclosure.反思为导向的计划的组成部分可以监视执行一项外壳代码和可以修改自己根据期望的目标相关的附文。 This is typically accomplished by dynamically assigning program code at runtime.这通常是通过动态分配的程序代码在运行。

Reflection can also be used to adapt a given program to different situations dynamically.反射还可以用来适应某一特定程序,以不同的情况动态。 For example, consider an application that uses two different classes X and Y interchangeably to perform similar operations.例如,考虑一个应用程序使用两种不同类别X和Y相互执行类似行动。 Withoutreflection-oriented programming, the application might be hard-coded tocall method names of class X and class Y. However, using thereflection-oriented programming paradigm, the application could bedesigned and written to utilize reflection in order to invoke methodsin classes X and Y without hard-coding method names.无反射导向编程,应用程序可能是硬编码调用方法的类的名字X和阶级元,但使用的反思为导向的编程范例,应用程序可能是精心设计和撰写,利用反射,以便在调用方法班X和Y没有硬编码方法的名字。 Reflection-orientedprogramming almost always requires additional knowledge, framework,relational mapping, and object relevance in order to take advantage ofmore generic code execution.反思面向几乎总是需要更多的知识,框架,关系映射,对象的相关性,以便利用更通用的代码执行。 Hard-coding can be avoided to the extent that reflection-oriented programming is used.硬编码,可避免的程度反映为导向的规划使用。

Reflection is also a key strategy for metaprogramming.反思也是一个关键的战略元程序。

Implementation执行
Alanguage supporting reflection provides a number of features availableat runtime that would otherwise be very obscure or impossible toaccomplish in a lower-level language.语言支持反思提供了一些功能,在运行时,否则是很模糊或者根本不可能实现在较低级别的语言。 Some of these features are the abilities to:其中一些功能的能力:

*Discover and modify source code constructions (such as code blocks,classes, methods, protocols, etc.) as a first-class object at runtime. * Discover和修改源代码结构(如代码块,类,方法,议定书等)作为一个一流的对象在运行时。
*Convert a string matching the symbolic name of a class or function intoa reference to or invocation of that class or function. *转换为字符串匹配的象征性名称的一类或函数的引用或调用的类或函数。
* Evaluate a string as if it were a source code statement at runtime. *评估字符串仿佛那是一个源代码在运行时的发言。

These features can be implemented in different ways.这些功能可以实现不同的方式。 In MOO, reflection forms a natural part of everyday programming idiom.在茂,体现自然形式的一部分,每天的节目成语。 Whenverbs (methods) are called, various variables such as verb (the name ofthe verb being called) and this (the object on which the verb iscalled) are populated to give the context of the call.当动词(方法)的要求,各种变量,如动词(的名称动词被称为) ,这(对其中的对象是所谓的动词)的居民提供的背景下要求。 Securityis typically managed by accessing the caller stack programmatically:Since callers() is a list of the methods by which the current verb waseventually called, performing tests on callers() (the command invokedby the original user) allows the verb to protect itself againstunauthorised use.安全通常是由访问的调用堆栈编程:自从来电( )列出所采用的方法目前动词而最终称之为,表演测试来电( ) (命令援引原用户)允许动词保护自己免受未经授权的使用。

Compiled languages rely on their runtime system to provide information about the source code.汇编语言依赖于他们的运行系统,以提供有关源代码。 Acompiled Objective-C executable, for example, records the names of allmethods in a block of the executable, providing a table to correspondthese with the underlying methods (or selectors for these methods)compiled into the program.编译目的碳可执行文件,例如,记录的名字,所有的方法在一个块的可执行文件,提供了对应这些表的基本方法(或“蔚恼庑┓椒ǎ┍嗳氤绦颉 Ina compiled language that supports runtime creation of functions, suchas Common Lisp, the runtime environment must include a compiler or aninterpreter.于汇编语言,支持运行时创建的职能,如共同Lisp语言的运行环境都必须包括一个编译器或翻译。

Reflectioncan be implemented for languages not having built-in reflectionfacilities by using a program transformation system to define automatedsource code changes..反思可以执行的语言没有内置反射设施的使用程序转换系统自动确定的源代码的变化..

Examples:例如:

Java爪哇

The following is an example in Java using the Java package java.lang.reflect.下面是一个示例Java中使用的Java软件包java.lang.reflect 。 Consider two pieces of code考虑两段代码

// Without reflection / /没有反射
Foo foo = new Foo();美孚美孚=新美孚( ) ;
foo.hello(); foo.hello ( ) ;

// With reflection / /反射
Class cls = Class.forName(”Foo”);一流的华彩= Class.forName ( “富” ) ;
Object foo = cls.newInstance();对象美孚= cls.newInstance ( ) ;
Method method = cls.getMethod(”hello”, null);方法方法= cls.getMethod ( “你好” ,空) ;
method.invoke(foo, null); method.invoke ( foo的,无效) ;

Both code fragments create an instance of a class Foo and call its hello() method.代码片段创建的一个实例级美孚,并呼吁其您好( )方法。 Thedifference is that, in the first fragment, the names of the class andmethod are hard-coded; it is not possible to use a class of anothername.不同的是,在第一个片段的名称,类别和方法,硬编码,这是无法使用一类的另一个名称。 In the second fragment, the names of the class and method can easily be made to vary at runtime.在第二个片段的姓名,类和方法可以很容易地取得了在运行时不同。 The downside is that the second version is harder to read, and is not protected by compile-time syntax and semantic checking.缺点是,第二个版本是难以阅读,而不是保护的编译时的语法和语义检查。 For example, if no class Foo exists, an error will be generated at compile time for the first version.例如,如果没有一流的美孚存在,一个错误会在编译时产生的第一个版本。 The equivalent error will only be generated at run time for the second version.相当于错误将只在运行时产生的第二个版本。

Perl的Perl

Here is an equivalent example in Perl:下面是一个相当于例如在Perl :

# without reflection #没有反思
my $foo = Foo->new();我的$ foo的=美孚- > “新建( ) ;
$foo->hello(); $ foo的, “您好( ) ;

# with reflection #与反思
my $class  = “Foo”;我的$级= “富贵” ;
my $method = “hello”;我的$方法= “你好” ;
my $object = $class->new();我的$对象= $类> “新建( ) ;
$object->$method(); $对象“ $方法( ) ;

PHP PHP的

Here is an equivalent example in PHP.下面是一个相当于例如在PHP 。

This is the non-reflective way to invoke Foo::hello:这是非反射方式援引美孚: :您好:

$Foo = new Foo(); $富贵=新美孚( ) ;
$Foo->hello(); $富昌“您好( ) ;

Usingreflection the class and method are retrieved as reflection objects andthen used to create a new instance and invoke the method.利用反射的类和方法,取自作为反射物体,然后用来建立一个新的实例,并调用该方法。

$f = new ReflectionClass(”Foo”); $女=新ReflectionClass ( “富” ) ;
$m = $f->GetMethod(”hello”);百万美元= $的F - “ GetMethod ( ”你好“ ) ;
$m->invoke( $f->newInstance() );百万美元, “援引( $的F - ” newInstance ( ) ) ;

Ruby红宝石

Here is an equivalent example in Ruby:下面是一个相当于例如红宝石:

# without reflection #没有反思
Foo.new.hello Foo.new.hello

# with reflection #与反思
Object.const_get(:Foo).new.send(:hello) Object.const_get ( :美孚) 。 new.send ( :您好! )

0

阅读 评论 收藏 转载 喜欢 打印举报/Report
  • 评论加载中,请稍候...
发评论

    发评论

    以上网友发言只代表其个人观点,不代表新浪网的观点或立场。

      

    新浪BLOG意见反馈留言板 电话:4000520066 提示音后按1键(按当地市话标准计费) 欢迎批评指正

    新浪简介 | About Sina | 广告服务 | 联系我们 | 招聘信息 | 网站律师 | SINA English | 会员注册 | 产品答疑

    新浪公司 版权所有