JavaScript must be enabled in order for you to view this page. However, it seems JavaScript is either disabled or not supported by your browser. To view this page, enable JavaScript by changing your browser options, then Try again! .

Reflection

by solo L2008-04-20T20:08:00Z,tag:Language

反射是一个处理过程,通过该过程程序可以查看和修改它自己的结构和行为。反射在高级别的虚拟机语言中比较常见,在低级别的语言中不常见。

Wikipedia中提到了两种反射:

  1. 运行时(或动态)反射
  2. 编译时(或静态)反射

反射可以用来:

  1. 在运行时发现和修改源代码的构造
  2. 将与类或函数的符号名匹配的字符串转换成对类的引用或对函数的调用
  3. 在运行时计算一个字符串,该字符串为一段源代码

示例(这些示例来自Wikipedia),我只选择了熟悉的:

Java

// Without reflection
Foo foo = new Foo();
foo.hello();
 
// With reflection
Class cls = Class.forName("Foo");
Method method = cls.getMethod("hello"null);
method.invoke(cls.newInstance()null);

C#

//Without reflection
Foo foo = new Foo();
foo.Hello();

//With reflection
Type t = Assembly.GetCallingAssembly().GetType("FooNamespace.Foo");
t.InvokeMember("Hello", BindingFlags.InvokeMethod, null, Activator.CreateInstance(t), null);

ActionScript

// Without reflection
var foo:Foo = new Foo();
foo.hello();

// With reflection
var ClassReference:Class = flash.utils.getDefinitionByName("Foo") as Class;
var instance:Object = new ClassReference();
instance.hello();

ECMAScript (JavaScript)

// Without reflection
new Foo().hello()

// With reflection

// assuming that Foo resides in this
(new this['Foo']()) ['hello']()

// or without assumption
(new (eval('Foo'))()) ['hello']()

PHP

# without reflection
$Foo = new Foo();
$Foo->hello();

# with reflection
$class = "Foo";
$method = "hello";
$object = new $class();
$object->$method();

Update:

Python

>>> # Class definition
>>> class Foo(object):
... def Hello(self):
... print "Hi"
...
>>> # Instantiation
>>> foo = Foo()
>>> # Normal call
>>> foo.Hello()
Hi
>>> # Evaluate a string in the context of the global namespace
>>> eval("foo.Hello()", globals())
Hi
>>> # Interpret distinct instance & method names from strings
>>> instance = 'foo'
>>> method = 'Hello'
>>> getattr(globals()[instance], method)()
Hi
Copyright © SoloL.org 冀ICP备06003230号