Reflective programming

In computer science, reflective programming or reflection is the ability of a process to examine, introspect, and modify its own structure and behavior.[1]

Historical background

The earliest computers were programmed in their native assembly languages, which were inherently reflective, as these original architectures could be programmed by defining instructions as data and using self-modifying code. As the bulk of programming moved to higher-level compiled languages such as Algol, Cobol, Fortran, Pascal, and C, this reflective ability largely disappeared until new programming languages with reflection built into their type systems appeared.[citation needed]

Brian Cantwell Smith's 1982 doctoral dissertation introduced the notion of computational reflection in procedural programming languages and the notion of the meta-circular interpreter as a component of 3-Lisp.[2][3]

Uses

Reflection helps programmers make generic software libraries to display data, process different formats of data, perform serialization and deserialization of data for communication, or do bundling and unbundling of data for containers or bursts of communication.

Effective use of reflection almost always requires a plan: A design framework, encoding description, object library, a map of a database or entity relations.

Reflection makes a language more suited to network-oriented code. For example, it assists languages such as Java to operate well in networks by enabling libraries for serialization, bundling and varying data formats. Languages without reflection such as C are required to use auxiliary compilers for tasks like Abstract Syntax Notation to produce code for serialization and bundling.

Reflection can be used for observing and modifying program execution at runtime. A reflection-oriented program component can monitor the execution of an enclosure of code and can modify itself according to a desired goal of that enclosure. This is typically accomplished by dynamically assigning program code at runtime.

In object-oriented programming languages such as Java, reflection allows inspection of classes, interfaces, fields and methods at runtime without knowing the names of the interfaces, fields, methods at compile time. It also allows instantiation of new objects and invocation of methods.

Reflection is often used as part of software testing, such as for the runtime creation/instantiation of mock objects.

Reflection is also a key strategy for metaprogramming.

In some object-oriented programming languages such as C# and Java, reflection can be used to bypass member accessibility rules. For C#-properties this can be achieved by writing directly onto the (usually invisible) backing field of a non-public property. It is also possible to find non-public methods of classes and types and manually invoke them. This works for project-internal files as well as external libraries such as .NET's assemblies and Java's archives.

Implementation

A language that supports reflection provides a number of features available at runtime that would otherwise be difficult to accomplish 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 first-class objects at runtime.
  • Convert a string matching the symbolic name of a class or function into a reference to or invocation of that class or function.
  • Evaluate a string as if it were a source-code statement at runtime.
  • Create a new interpreter for the language's bytecode to give a new meaning or purpose for a programming construct.

These features can be implemented in different ways. In MOO, reflection forms a natural part of everyday programming idiom. When verbs (methods) are called, various variables such as verb (the name of the verb being called) and this (the object on which the verb is called) are populated to give the context of the call. Security is typically managed by accessing the caller stack programmatically: Since callers() is a list of the methods by which the current verb was eventually called, performing tests on callers()[0] (the command invoked by the original user) allows the verb to protect itself against unauthorised use.

Compiled languages rely on their runtime system to provide information about the source code. A compiled Objective-C executable, for example, records the names of all methods in a block of the executable, providing a table to correspond these with the underlying methods (or selectors for these methods) compiled into the program. In a compiled language that supports runtime creation of functions, such as Common Lisp, the runtime environment must include a compiler or an interpreter.

Reflection can be implemented for languages without built-in reflection by using a program transformation system to define automated source-code changes.

Security considerations

Reflection may allow a user to create unexpected control flow paths through an application, potentially bypassing security measures. This may be exploited by attackers.[4] Historical vulnerabilities in Java caused by unsafe reflection allowed code retrieved from potentially untrusted remote machines to break out of the Java sandbox security mechanism. A large scale study of 120 Java vulnerabilities in 2013 concluded that unsafe reflection is the most common vulnerability in Java, though not the most exploited.[5]

Examples

The following code snippets create an instance foo of class Foo and invoke its method 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:

(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)))

C#

The following is an example in 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);

Delphi, Object Pascal

This Delphi and Object Pascal example assumes that a TFoo class has been declared in a unit called Unit1:

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;

eC

The following is an example in 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);

Go

The following is an example in 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)
}

Java

The following is an example in 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) {}

JavaScript

The following is an example in 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()')

Julia

The following is an example in Julia:

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

Objective-C

The following is an example in Objective-C, implying either the OpenStep or Foundation Kit framework is used:

// 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)];

Perl

The following is an example in 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;";

PHP

The following is an example in PHP:[6]

// 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);

Python

The following is an example in Python:

# Without reflection
obj = Foo()
obj.hello()

# With reflection
obj = globals()["Foo"]()
getattr(obj, "hello")()

# With eval
eval("Foo().hello()")

R

The following is an example in 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))

Ruby

The following is an example in 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"

Xojo

The following is an example using Xojo:

' 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

See also

References

Citations

  1. ^ A Tutorial on Behavioral Reflection and its Implementation by Jacques Malenfant et al. (PDF), unknown, archived from the original (PDF) on 21 August 2017, retrieved 23 June 2019
  2. ^ Brian Cantwell Smith, Procedural Reflection in Programming Languages, Department of Electrical Engineering and Computer Science, Massachusetts Institute of Technology, PhD dissertation, 1982.
  3. ^ Brian C. Smith. Reflection and semantics in a procedural language Archived 2015-12-13 at the Wayback Machine. Technical Report MIT-LCS-TR-272, Massachusetts Institute of Technology, Cambridge, Massachusetts, January 1982.
  4. ^ Barros, Paulo; Just, René; Millstein, Suzanne; Vines, Paul; Dietl, Werner; d'Amorim, Marcelo; Ernst, Michael D. (August 2015). Static Analysis of Implicit Control Flow: Resolving Java Reflection and Android Intents (PDF) (Report). University of Washington. UW-CSE-15-08-01. Retrieved October 7, 2021.
  5. ^ Eauvidoum, Ieu; disk noise (October 5, 2021). "Twenty years of Escaping the Java Sandbox". Phrack. Vol. 10, no. 46. Retrieved October 7, 2021.
  6. ^ "PHP: ReflectionClass - Manual". www.php.net.

Sources

Further reading

  • Ira R. Forman and Nate Forman, Java Reflection in Action (2005), ISBN 1-932394-18-4
  • Ira R. Forman and Scott Danforth, Putting Metaclasses to Work (1999), ISBN 0-201-43305-2

Read other articles:

CBC Radio One station in Sydney, Nova Scotia CBISydney, Nova ScotiaBroadcast areaCape Breton IslandFrequency1140 kHz (AM)BrandingCBC Radio OneProgrammingFormatNews–talkOwnershipOwnerCanadian Broadcasting CorporationSister stationsCBI-FMHistoryFirst air dateNovember 1, 1948Former frequencies1570 kHz (1948–1955)Call sign meaningCape Breton IslandTechnical informationLicensing authorityCRTCClassBPower10,000 wattsTransmitter coordinates46°08′09″N 60°16′10″W / 46.1358...

 

Sports complex in Germantown, Maryland, United States Maryland SoccerPlexMaureen Hendricks Field at Maryland SoccerplexLocation18031 Central Park CircleBoyds, Maryland, U.S.OwnerMaryland Soccer FoundationMontgomery County, Maryland, U.S.OperatorMaryland Soccer FoundationCapacity5,000[1]SurfaceBermuda Grass (9 fields) Bluegrass (11 fields) Bermuda Grass Stadium, 21 natural grass fields)Artificial turf (3 fields)ConstructionBroke ground1999Opened2000TenantsWashington Freedom Futures (W-...

 

P13 DJKAStasiun LRT PalembangLokasiJalan Gubernur H. A Bastari, Sungai Kedukan, Rambutan, Banyuasin, Sumatera SelatanIndonesiaOperatorDivre III PalembangJalurP Lin PalembangJumlah peron2 peron sisiJumlah jalur2Operator KAKereta Api IndonesiaKonstruksiJenis strukturLayangParkirAdaFasilitas sepedaN/AAkses difabelYaInformasi lainKode stasiunDJKSejarahDibuka1 Agustus 2018 (2018-08-01)Operasi layanan Stasiun sebelumnya LRT Palembang Stasiun berikutnya Jakabaringke arah Bandara Sultan Mahmud B...

هذه المقالة يتيمة إذ تصل إليها مقالات أخرى قليلة جدًا. فضلًا، ساعد بإضافة وصلة إليها في مقالات متعلقة بها. (سبتمبر 2016) مركزات بروتين الأوراق (Leafu) المصنوعة من القراص الكبير إن مركزات بروتين الأوراق (LPC) هي صورة مركزة من البروتينات الموجودة في أوراق النباتات.[1][2] وقد تم...

 

Defunct airline of the United States and Germany (1978–2017) Air Berlin IATA ICAO Callsign AB BER AIR BERLIN Founded1978 (1978)(as Air Berlin USA)Commenced operations28 April 1979 (1979-04-28)(as Air Berlin USA)1991 (1991)(as Air Berlin GmbH & Co. Luftverkehrs KG)Ceased operations27 October 2017 (2017-10-27)HubsBerlin–TegelDüsseldorfFocus citiesPalma de MallorcaFrequent-flyer programtopbonusAllianceOneworld (2012–2017)SubsidiariesBelair (2001...

 

Jean-Guenolé-Marie DaniélouS.J.Kardinal-Diaken San SabaGiorgio La Pira dan Daniélou di Firenze, 1953GerejaRoman Catholic ChurchMasa jabatan30 April 1969 - 20 Mei 1974PendahuluAugustin BeaPenerusJoseph SchröfferImamatTahbisan imam20 Agustus 1938Tahbisan uskup19 April 1969oleh François MartyPelantikan kardinal28 April 1969oleh Paus Paulus VIInformasi pribadiNama lahirJean-Guenolé-Marie DaniélouLahir(1905-05-14)14 Mei 1905Neuilly-sur-Seine, PrancisWafat20 Mei 1974(1974-05-20) (umur&#...

1930 film Big BoyDirected byAlan CroslandWritten byWilliam K. WellsRex Taylorbased on a musical comedy by Harold AtteridgeStarringAl JolsonClaudia DellLouise Closser HaleNoah BeeryCinematographyHal MohrEdited byRalph DawsonMusic byRex DunnAlois ReiserSam H. SteptBud GreenDistributed byWarner Bros.Release date September 11, 1930 (1930-09-11) Running time68 minutesCountryUnited StatesLanguageEnglishBudget$574,000 [1]Box office$498,000[1] Big Boy is a 1930 American...

 

Marco Armellino Nazionalità  Italia Altezza 186 cm Peso 70 kg Calcio Ruolo Centrocampista Squadra  Avellino CarrieraGiovanili 20??-2008 Vico EquenseSquadre di club1 2008-2010 Vico Equense63 (3)[1]2010-2012 Sorrento42 (0)2012-2013 Reggina38 (2)2013-2014→  Cremonese24 (3)[2]2014-2015 Reggina35 (3)[3]2015-2017 Matera62 (13)[4]2017-2019 Lecce43 (4)2019-2021 Monza68 (6)[5]2021-2023 Modena65 (5)2...

 

此條目可参照英語維基百科相應條目来扩充。 (2021年5月6日)若您熟悉来源语言和主题,请协助参考外语维基百科扩充条目。请勿直接提交机械翻译,也不要翻译不可靠、低品质内容。依版权协议,译文需在编辑摘要注明来源,或于讨论页顶部标记{{Translated page}}标签。 约翰斯顿环礁Kalama Atoll 美國本土外小島嶼 Johnston Atoll 旗幟颂歌:《星條旗》The Star-Spangled Banner約翰斯頓環礁�...

Disambiguazione – Murales rimanda qui. Se stai cercando altri significati, vedi Murales (disambigua). Un murale (o impropriamente murales, derivato dal plurale spagnolo di mural[1][2][3]) è un dipinto realizzato su una parete, un soffitto o altra larga superficie permanente in muratura. Il termine indica anche il genere di pittura, ed è divenuto celebre per il movimento artistico messicano noto come muralismo. Indice 1 Descrizione 2 Nel mondo 2.1 In German...

 

Core ecoregion of Japan Taiheiyo evergreen forestsNametoko Ravine in Ashizuri-Uwakai National ParkEcologyRealmPalearcticBiometemperate broadleaf and mixed forestsBordersNihonkai evergreen forestsNihonkai montane deciduous forests,Taiheiyo montane deciduous forestsGeographyArea135,819 km2 (52,440 sq mi)CountryJapanConservationConservation statusCritical/endangeredProtected23,487 km² (17%)[1] The Taiheiyo evergreen forests is a temperate broadleaf forest ecoregion of Jap...

 

Pertempuran Laut HakodateBagian dari Perang BoshinPertempuran laut Teluk Hakodate, Mei 1869: di latar belakang Kasuga dan Kōtetsu milik Angkatan Laut Kekaisaran JepangTanggal4 Mei 1869 – 10 Mei 1869LokasiTeluk HakodateHasil Kemenangan telak pihak kekaisaranPihak terlibat Kekaisaran Jepang: Kōtetsu Kasuga Hiryū Teibo Yoharu Moshun Chōyō Republik Ezo: Kaiten Banryū Chiyodagata Chōgei MikahoTokoh dan pemimpin Arai IkunosukeKekuatan 8 kapal perang bertenaga uap 5 kapal perang bertenaga u...

Residential community developed by streetcar lines This article possibly contains original research. Please improve it by verifying the claims made and adding inline citations. Statements consisting only of original research should be removed. (June 2023) (Learn how and when to remove this message) A streetcar suburb is a residential community whose growth and development was strongly shaped by the use of streetcar lines as a primary means of transportation. Such suburbs developed in the Unit...

 

  هذه المقالة عن دولة في القرن الأفريقي. لالمملكة القديمة، طالع بنط.   أرض البنط ولاية أرض البنط الصومالية  أرض البنطعلم أرض البنط  أرض البنطالشعار   الأرض والسكان إحداثيات 8°24′N 48°30′E / 8.4°N 48.5°E / 8.4; 48.5   المساحة 212510 كيلومتر مربع  عاصمة غاروي...

 

Come ti rovino le vacanzeUna scena del filmTitolo originaleVacation Lingua originaleinglese Paese di produzioneStati Uniti d'America Anno2015 Durata99 min Generecommedia, avventura RegiaJohn Francis Daley, Jonathan M. Goldstein SoggettoJohn Hughes (personaggi) SceneggiaturaJohn Francis Daley, Jonathan M. Goldstein ProduttoreChris Bender, David Dobkin Produttore esecutivoRichard Brener, Toby Emmerich, Marc S. Fischer, Jeff Kleeman, Dave Neustadter, Samuel J. Brown Casa di produzioneBenderS...

Pour les articles homonymes, voir Safo (homonymie). Pour l’article ayant un titre homophone, voir Sapho. Cet article est une ébauche concernant une localité malienne. Vous pouvez partager vos connaissances en l’améliorant (comment ?) selon les recommandations des projets correspondants. Safo Administration Pays Mali Région Koulikoro Cercle Kati Maire Magnan Kané (CDS) Démographie Population 16 066 hab. (2009) Population précédent recensement 7 923 hab. G�...

 

Scottish participation in the Thirty Years' War Scottish soldiers in the service of Gustavus Adolphus of Sweden; 1631 German engraving There was a complicated involvement between Scotland and the Thirty Years' War of 1618–1648. Scotland and the Scots were heavily entangled in both the diplomatic and military events which centred on the Holy Roman Empire. There were a number of reasons for this participation. Among these, the fate of the Scottish princess Elizabeth of Bohemia (daughter of Ki...

 

Discipline concerning the application of advanced analytical methods For the academic journal, see Operations Research (journal). The examples and perspective in this article may not represent a worldwide view of the subject. The specific issue is: US perspective completely neglected, George Dantzig gets a passing mention only You may improve this article, discuss the issue on the talk page, or create a new article, as appropriate. (December 2020) (Learn how and when to remove this message) O...

Journey into the underworld in literature For the Antarctic wind, see Katabatic wind. For other uses, see Katabasis (disambiguation). Odysseus consults the soul of the prophet Tiresias in his katabasis during Book 11 of The Odyssey. A katabasis or catabasis (Ancient Greek: κατάβασις, romanized: katábasis, lit. 'descent'; from κατὰ (katà) 'down' and βαίνω (baínō) 'go') is a journey to the underworld. Its original sense is usuall...

 

Byzantine emperor from 1282 to 1328 This article is about the Byzantine emperor. For the emperor of Trebizond, see Andronikos II of Trebizond. Andronikos II PalaiologosEmperor and Autocrat of the RomansMiniature from the manuscript of George Pachymeres' HistoriaByzantine emperorReign11 December 1282 –24 May 1328Coronation8 November 1272PredecessorMichael VIII Palaiologos (alone)SuccessorAndronikos III PalaiologosCo-emperorMichael IX PalaiologosProclamation1261 (as co-emperor)Born25 March 12...