Open main menu
Home
Random
Recent changes
Special pages
Community portal
Preferences
About Wikipedia
Disclaimers
Incubator escapee wiki
Search
User menu
Talk
Dark mode
Contributions
Create account
Log in
Editing
Reflective programming
(section)
Warning:
You are not logged in. Your IP address will be publicly visible if you make any edits. If you
log in
or
create an account
, your edits will be attributed to your username, along with other benefits.
Anti-spam check. Do
not
fill this in!
==Examples== The following code snippets create an [[instance (computer science)|instance]] {{code|foo}} of [[class (computer science)|class]] {{code|Foo}} and invoke its [[method (computer science)|method]] {{code|PrintHello}}. For each [[programming language]], normal and reflection-based call sequences are shown. === Common Lisp === The following is an example in [[Common Lisp]] using the [[Common Lisp Object System]]: <syntaxhighlight lang="lisp"> (defclass foo () ()) (defmethod print-hello ((f foo)) (format T "Hello from ~S~%" f)) ;; Normal, without reflection (let ((foo (make-instance 'foo))) (print-hello foo)) ;; With reflection to look up the class named "foo" and the method ;; named "print-hello" that specializes on "foo". (let* ((foo-class (find-class (read-from-string "foo"))) (print-hello-method (find-method (symbol-function (read-from-string "print-hello")) nil (list foo-class)))) (funcall (sb-mop:method-generic-function print-hello-method) (make-instance foo-class))) </syntaxhighlight> === C# === The following is an example in [[C Sharp (programming language)|C#]]: <syntaxhighlight lang="c#"> // Without reflection var foo = new Foo(); foo.PrintHello(); // With reflection Object foo = Activator.CreateInstance("complete.classpath.and.Foo"); MethodInfo method = foo.GetType().GetMethod("PrintHello"); method.Invoke(foo, null); </syntaxhighlight> ===Delphi, Object Pascal=== This [[Delphi (software)|Delphi]] and [[Object Pascal]] example assumes that a {{mono|TFoo}} class has been declared in a unit called {{mono|Unit1}}: <syntaxhighlight lang="Delphi"> uses RTTI, Unit1; procedure WithoutReflection; var Foo: TFoo; begin Foo := TFoo.Create; try Foo.Hello; finally Foo.Free; end; end; procedure WithReflection; var RttiContext: TRttiContext; RttiType: TRttiInstanceType; Foo: TObject; begin RttiType := RttiContext.FindType('Unit1.TFoo') as TRttiInstanceType; Foo := RttiType.GetMethod('Create').Invoke(RttiType.MetaclassType, []).AsObject; try RttiType.GetMethod('Hello').Invoke(Foo, []); finally Foo.Free; end; end; </syntaxhighlight> ===eC=== The following is an example in eC: <syntaxhighlight lang=eC> // Without reflection Foo foo { }; foo.hello(); // With reflection Class fooClass = eSystem_FindClass(__thisModule, "Foo"); Instance foo = eInstance_New(fooClass); Method m = eClass_FindMethod(fooClass, "hello", fooClass.module); ((void (*)())(void *)m.function)(foo); </syntaxhighlight> ===Go=== The following is an example in [[Go (programming language)|Go]]: <syntaxhighlight lang="go"> import "reflect" // Without reflection f := Foo{} f.Hello() // With reflection fT := reflect.TypeOf(Foo{}) fV := reflect.New(fT) m := fV.MethodByName("Hello") if m.IsValid() { m.Call(nil) } </syntaxhighlight> ===Java=== The following is an example in [[Java (programming language)|Java]]: <syntaxhighlight lang="java"> import java.lang.reflect.Method; // Without reflection Foo foo = new Foo(); foo.hello(); // With reflection try { Object foo = Foo.class.getDeclaredConstructor().newInstance(); Method m = foo.getClass().getDeclaredMethod("hello", new Class<?>[0]); m.invoke(foo); } catch (ReflectiveOperationException ignored) {} </syntaxhighlight> ===JavaScript=== The following is an example in [[JavaScript]]: <syntaxhighlight lang="javascript"> // Without reflection const foo = new Foo() foo.hello() // With reflection const foo = Reflect.construct(Foo) const hello = Reflect.get(foo, 'hello') Reflect.apply(hello, foo, []) // With eval eval('new Foo().hello()') </syntaxhighlight> ===Julia=== The following is an example in [[Julia (programming language)|Julia]]: <syntaxhighlight lang="julia-repl"> julia> struct Point x::Int y end # Inspection with reflection julia> fieldnames(Point) (:x, :y) julia> fieldtypes(Point) (Int64, Any) julia> p = Point(3,4) # Access with reflection julia> getfield(p, :x) 3 </syntaxhighlight> ===Objective-C=== The following is an example in [[Objective-C]], implying either the [[OpenStep]] or [[Foundation Kit]] framework is used: <syntaxhighlight lang="ObjC"> // Foo class. @interface Foo : NSObject - (void)hello; @end // Sending "hello" to a Foo instance without reflection. Foo *obj = [[Foo alloc] init]; [obj hello]; // Sending "hello" to a Foo instance with reflection. id obj = [[NSClassFromString(@"Foo") alloc] init]; [obj performSelector: @selector(hello)]; </syntaxhighlight> ===Perl=== The following is an example in [[Perl]]: <syntaxhighlight lang="perl"> # Without reflection my $foo = Foo->new; $foo->hello; # or Foo->new->hello; # With reflection my $class = "Foo" my $constructor = "new"; my $method = "hello"; my $f = $class->$constructor; $f->$method; # or $class->$constructor->$method; # with eval eval "new Foo->hello;"; </syntaxhighlight> ===PHP=== The following is an example in [[PHP]]:<ref>{{cite web |title=PHP: ReflectionClass - Manual |url=https://www.php.net/manual/en/class.reflectionclass.php |website=www.php.net}}</ref> <syntaxhighlight lang="php"> // Without reflection $foo = new Foo(); $foo->hello(); // With reflection, using Reflections API $reflector = new ReflectionClass("Foo"); $foo = $reflector->newInstance(); $hello = $reflector->getMethod("hello"); $hello->invoke($foo); </syntaxhighlight> ===Python=== The following is an example in [[Python (programming language)|Python]]: <syntaxhighlight lang="python"> # Without reflection obj = Foo() obj.hello() # With reflection obj = globals()["Foo"]() getattr(obj, "hello")() # With eval eval("Foo().hello()") </syntaxhighlight> ===R=== The following is an example in [[R (programming language)|R]]: <syntaxhighlight lang="r"> # Without reflection, assuming foo() returns an S3-type object that has method "hello" obj <- foo() hello(obj) # With reflection class_name <- "foo" generic_having_foo_method <- "hello" obj <- do.call(class_name, list()) do.call(generic_having_foo_method, alist(obj)) </syntaxhighlight> ===Ruby=== The following is an example in [[Ruby (programming language)|Ruby]]: <syntaxhighlight lang="ruby"> # Without reflection obj = Foo.new obj.hello # With reflection obj = Object.const_get("Foo").new obj.send :hello # With eval eval "Foo.new.hello" </syntaxhighlight> ===Xojo=== The following is an example using [[Xojo]]: <syntaxhighlight lang="vbnet"> ' Without reflection Dim fooInstance As New Foo fooInstance.PrintHello ' With reflection Dim classInfo As Introspection.Typeinfo = GetTypeInfo(Foo) Dim constructors() As Introspection.ConstructorInfo = classInfo.GetConstructors Dim fooInstance As Foo = constructors(0).Invoke Dim methods() As Introspection.MethodInfo = classInfo.GetMethods For Each m As Introspection.MethodInfo In methods If m.Name = "PrintHello" Then m.Invoke(fooInstance) End If Next </syntaxhighlight>
Edit summary
(Briefly describe your changes)
By publishing changes, you agree to the
Terms of Use
, and you irrevocably agree to release your contribution under the
CC BY-SA 4.0 License
and the
GFDL
. You agree that a hyperlink or URL is sufficient attribution under the Creative Commons license.
Cancel
Editing help
(opens in new window)