Reflection (תכנות) – הבדלי גרסאות

תוכן שנמחק תוכן שנוסף
מאין תקציר עריכה
הרחבה
שורה 33:
בשפה מהודרת התומכת ביצירת פונקציות בזמן ריצה, כדוגמת [[Common Lisp]], סביבת ההרצה חייבת לכלול מהדר או מפרש. כמו כן, ניתן לממש reflection גם בשפות שאינן כוללות מנגנונים מובנים לתמיכה ב-reflection, על ידי שימוש במערכת ל-[[program transformation]], כדי להגדיר שינויים אוטומטיים בקוד המקור.
 
== דוגמאות ==
קטעי הקוד הבאים יוצרים [[מופע (מדעי המחשב)|מופע]] <code>foo</code> של ה[[מחלקה (תכנות)|מחלקה]] <code>Foo</code>, ואז קוראים למתודה <code>hello</code>. עבור כל [[שפת תכנות]], מוצגות הקריאות הרגילות וגם הקריאות שעושות שימוש ב-reflection.
 
<div style="direction:ltr;">
 
=== [[Java]] ===
<source lang="java">
// Using Java package: java.lang.reflect
 
// Without reflection
new Foo().hello();
 
// With reflection
Class<?> clazz = Class.forName("Foo");
clazz.getMethod("hello").invoke(clazz.newInstance());
</source>
 
 
=== [[JavaScript]] ===
<source lang="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']()
 
// or simply
eval('new Foo().hello()')
</source>
 
 
=== [[PHP]] ===
<syntaxhighlight lang=php>
// without reflection
$foo = new Foo();
$foo->hello();
 
// with reflection
$reflector = new ReflectionClass('Foo');
$foo = $reflector->newInstance();
$hello = $reflector->getMethod('hello');
$hello->invoke($foo);
 
// using callback
$foo = new Foo();
call_user_func(array($foo, 'hello'));
 
// using variable variables syntax
$className = 'Foo';
$foo = new $className();
$method = 'hello';
$foo->$method();
</syntaxhighlight>
 
 
=== [[Ruby]] ===
<syntaxhighlight lang=ruby>
# without reflection
obj = Foo.new
obj.hello
 
# with reflection
class_name = "Foo"
method = :hello
obj = Kernel.const_get(class_name).new
obj.send method
</syntaxhighlight>
 
 
=== [[Objective-C]] ===
<syntaxhighlight lang=objc>
// Foo class
@interface Foo : NSObject
- (void)hello;
//...
@end
 
// without reflection
Foo *obj = [[Foo alloc] init];
[obj hello];
 
// with reflection in OPENSTEP, loading class and call method using variables.
NSString *className = @"Foo";
SEL selector = @selector(hello);
id obj = [[NSClassFromString(className) alloc] init];
[obj performSelector:selector]; // This will emit an warning when compiling with Objective-C ARC.
</syntaxhighlight>
</div>
 
[[קטגוריה:תכנות]]