Some languages like Dart use mirror based reflection so, in simple terms, what is the difference between such implementation and traditional reflection as you see in C# or Java.
Update:
I found this excellent (and somewhat quirky) video by Gilad Bracha on Mirror based reflection in Newspeak.
http://www.hpi.uni-potsdam.de/hirschfeld/events/past/media/100105_Bracha_2010_LinguisticReflectionViaMirrors_HPI.mp4 (mirror stuff starts at 7:42)
For many uses, I don't think mirrors will be that different than Java reflection. The most important thing understand about mirrors is that they decouple the reflection API from the standard object API, so instead of obj.getClass() you use reflect(obj). It's a seemingly small difference, but it gives you a few nice things:
The object API isn't polluted, and there's no danger of breaking reflection by overriding a reflective method.
You can potentially have different mirror systems. Say, one that doesn't allow access to private methods. This could end up being very useful for tools.
The mirror system doesn't have to be included. For compiling to JS this can be important. If mirrors aren't used then there's no out-of-band to access code and pruning becomes viable.
Mirrors can be made to work on remote code, not just local code, since you don't need the reflected object to be in the same Isolate or VM as the mirror.
Here's how mirrors are different than reflection in Java and Javascript when used to get an object's methods:
Java:
myObject.getClass().getMethods(); // returns an array
Dart:
reflect(myObject).type.methods; // returns a map
Javascript:
var methods = [];
for (var m in myObject) {
if (typeof m === 'function') {
methods.push(m);
}
}
Your best bet is this article by Gilad Bracha, Dart's co-designer and specification author. To get a glimpse, it will probably be enough to read the first chapter.
The abstract claims that mirrors adhere to three necessary principles that aren't followed by traditional reflection:
We identify three design principles for reflection and metaprogramming
facilities in object oriented programming languages. Encapsulation:
meta-level facilities must encapsulate their implementation.
Stratification: meta-level facilities must be separated from
base-level functionality. Ontological correspondence: the ontology of
meta-level facilities should correspond to the ontology of the
language they manipulate. Traditional/mainstream reflective
architectures do not follow these precepts. In contrast, reflective
APIs built around the concept of mirrors are characterized by
adherence to these three principles.
I would also point you to this other recent answer by Gilad, where he lists some other great reference material: How to get concrete object of a static method via mirror API?
Related
My requirement is to use some kind of metadata system for the entities we use, but extensible, meaning that we need to support some kind of custom metadata additionally to querying for properties and methods. The standard Type/TypeInfo classes are useful to some extent, but they cannot be customized to add specific properties to support various patterns we have: tree nodes, master-detail, and other.
Kephas.Model provides a complex infrastructure for supporting such cases, including advanced features like mixins and dimensions, but this is however a bit too much for our system. We need something more lightweight for the code-first entities we have.
Is there a suggestion about what can we use for this kind of requirements? I noticed the Kephas.Reflection namespace, and this seems like a proper candidate, but I am not sure how to use it properly.
That's right, Kephas.Runtime namespace provides a lightweight extensible metadata through the base IRuntimeTypeInfo interface (in Kephas.Core package). There are mainly two ways of accessing it using extension methods:
// get the type information from an object/instance.
var typeInfo = obj.GetRuntimeTypeInfo();
// convert a Type/TypeInfo to a IRuntimeTypeInfo
typeInfo = type.AsRuntimeTypeInfo();
From here on you can manipulate properties, fields, methods, annotations (attributes), and so on, typically indexed by their names. A very nice feature is that IRuntimeTypeInfo is an expando, allowing adding of dynamic values at runtime.
Please note that IRuntimeTypeInfo specializes ITypeInfo (in Kephas.Reflection namespace), which is the base interface in Kephas.Model, too. You are right that Kephas.Model provides a more complex functionality which might make sense for a more elaborate metadata model, including entities, services, activities, and whatever classifiers you can think of, as well as loading the model also from sources other than the .NET reflection (JSON, XML, database, so on).
Another aspect is that up to version 5.2.0, the IRuntimeTypeInfo would be implemented by the sealed RuntimeTypeInfo class. Starting with version 5.3.0, it will be possible to provide your own implementations, which can be more than one.
I seldom see static analyzer for functional programming languages, like Racket/Scheme, I even doubt that whether there are any. I would like to write a static analyzer for functional languages, say Scheme/Racket. How should I go about it?
Yes, there is some work on static analysis of dynamic languages like Scheme. For instance, see the work of Olin Shivers (http://www.ccs.neu.edu/home/shivers/citations.html) and Manuel Serrano (http://www-sop.inria.fr/members/Manuel.Serrano/index-1.html).
There's already, e.g., typed racket: http://docs.racket-lang.org/ts-guide/index.html
Since valid racket code is valid typed racket, you just have to change the language you're working in. Then, for libraries with typed versions, load those instead of the untyped versions, and certain type errors can get caught statically already. Further type annotations can be added to your own code to get guarantees of type correctness beyond that...
First read this paper by Shivers, explaining why there is no static control flow graph available in Scheme.
Might implemented k-CFA in Scheme. Matt Might's site and blog is a good starting point for exploring static analysis of higher-order languages.
I did some static analysis implementations for Scheme in Java as well:
k-CFA implementation
Interprocedural Dependence Analysis implementation based on a paper by Might and Prabhu
From what I gather, Gosu is simply C# for the JVM (which is a good thing). Is it true? What are some difference between Gosu and C# (Except the class library and the fact it runs on JVM) ?
We didn't build Gosu to be one language or the other for the JVM. Rather we built Gosu to be a useful language for the JVM. In addition, we recognized that Gosu needed to be familiar to the multitudes of existing programmers who are most comfortable with the imperative, object-oriented model. To achieve that we borrowed heavily from several languages e.g., Java, C#, EcmaScript, Ruby, and some others. The result, we think, is a language that is uniquely positioned on the JVM.
What is entirely unique about Gosu, however, is it's open type system.
Gosu's type system consists of a configurable number of type loaders. A type loader's primary responsibility is to resolve a type name in its domain and return an implementation of Gosu's IType interface. This is what is most unique about Gosu -- its type system is open to other domains to participate with first-class representation. I frequently use the term, DST (Domain Specific Type), to get across the idea. For instance, Gosu does not discriminate between a Gosu Class a Java Class or XML Type or what have you; they're all just types to Gosu's compiler. Check out the DynamicType example in the download to get a glimpse of the power and breadth the open type system provides. Essentially, the example demonstrates that C#'s "dynamic types where required" can simply be a new type loader domain in Gosu. Or check out the Ronin framework to see how easily the web and database domains can map seamlessly into Gosu.
It is important to understand that not all type loader domains in Gosu are required to produce bytecode. Those that do implement an interface for getting at the corresponding Java class. Those that don't provide call handlers and property accessors for reflective MethodInfo and PropertyInfo evaluation, respectively. Note all types provide TypeInfo, see IType.getTypeInfo(). For instance, the parser works against the TypeInfo, MethodInfo, etc. abstractions as the means for a level playing field between disparate types. At runtime, however, unless a type provides a Java bytecode class the MethodInfos and PropertyInfos also are responsible for handling calls.
No. If you look at the "notable differences" page (differences between Java and Gosu) you'll see a lot of things which are like C#, but also things which aren't in C# such as case-insensitivity and making semi-colons optional. There are also things which certainly aren't mentioned but which are part of C#:
Custom value types
Operator overloading
LINQ
Dynamic typing where required
I think it would be a mistake to regard Gosu as "C# for the JVM" rather than "a JVM language which mixes bits of Java, bits of C# and some bits from other languages too".
I'm relatively new to flash, and is confused about what I should use to store and retrieve key value pairs. After some googling I've found various map-like things to choose from:
1) Use a Object:
var map:Object = new Object();
map["key"] = "value";
The problem is that it seems to lack some very basic features. For example to even get the size of map I'd have to write a util method.
2) Use a Dictionary
What does this standard library class provide over the simple object? It seems silly for it to exist if it's functionally identical to Object.
3) Go download some custom HashMap/HashTable implementation from the web.
I've used a lot of modern languages, and this is the first time I haven't been able to find a library implementation of an associative array within 5 minutes. So I'd like to get some best-practice advice from an experienced flash developer.
Thanks!
Maybe your google foo is a bit weak today?
But you're right, the built-in Object object, doesn't provide many extra features.
Dictionaries have at least two important differences with Objects:
They can use any object as a key. For Objects, the key has to be a string (if you pass any other object, the toString() method will be implicitly called).
You can optionally set they keys to be weak referenced (this doesn't make much sense for Objects).
Anyway, there are a number of opensource libraries that implement various data structures and collection types.
Just from the top of my head:
http://lab.polygonal.de/ds/
http://sibirjak.com/blog/index.php/collections/as3commons-collections/
You should use whichever option is needed for a particular situation. There is no correct answer to say "always use 'x'".
I've found that the vast majority of times Object based dictionaries are all that's needed. They're extremely fast and easy to use and I almost never need the extra features. It converts any key to a string which works well for most situations.
Dictionary provides some extra features but I've never needed object-based keys (and I've been programming in Flex since 1.0 alpha 1). The only time I've used a Dictionary is as a hack to get access to a weak reference since Flex doesn't provide a simple weak reference class.
More complex dictionaries are available which will provide more functionality. If you really need this functionality, then they will be useful, but I wouldn't recommend jumping in to use them when a plain old Object will work find for your needs. That said, if you do turn out to need them in your application, it might be best to using the same 3rd-party dictionary everywhere in that app for consistency and easy of maintenance.
Recently I was talking to a co-worker about C++ and lamented that there was no way to take a string with the name of a class field and extract the field with that name; in other words, it lacks reflection. He gave me a baffled look and asked when anyone would ever need to do such a thing.
Off the top of my head I didn't have a good answer for him, other than "hey, I need to do it right now". So I sat down and came up with a list of some of the things I've actually done with reflection in various languages. Unfortunately, most of my examples come from my web programming in Python, and I was hoping that the people here would have more examples. Here's the list I came up with:
Given a config file with lines like
x = "Hello World!"
y = 5.0
dynamically set the fields of some config object equal to the values in that file. (This was what I wished I could do in C++, but actually couldn't do.)
When sorting a list of objects, sort based on an arbitrary attribute given that attribute's name from a config file or web request.
When writing software that uses a network protocol, reflection lets you call methods based on string values from that protocol. For example, I wrote an IRC bot that would translate
!some_command arg1 arg2
into a method call actions.some_command(arg1, arg2) and print whatever that function returned back to the IRC channel.
When using Python's __getattr__ function (which is sort of like method_missing in Ruby/Smalltalk) I was working with a class with a whole lot of statistics, such as late_total. For every statistic, I wanted to be able to add _percent to get that statistic as a percentage of the total things I was counting (for example, stats.late_total_percent). Reflection made this very easy.
So can anyone here give any examples from their own programming experiences of times when reflection has been helpful? The next time a co-worker asks me why I'd "ever want to do something like that" I'd like to be more prepared.
I can list following usage for reflection:
Late binding
Security (introspect code for security reasons)
Code analysis
Dynamic typing (duck typing is not possible without reflection)
Metaprogramming
Some real-world usages of reflection from my personal experience:
Developed plugin system based on reflection
Used aspect-oriented programming model
Performed static code analysis
Used various Dependency Injection frameworks
...
Reflection is good thing :)
I've used reflection to get current method information for exceptions, logging, etc.
string src = MethodInfo.GetCurrentMethod().ToString();
string msg = "Big Mistake";
Exception newEx = new Exception(msg, ex);
newEx.Source = src;
instead of
string src = "MyMethod";
string msg = "Big MistakeA";
Exception newEx = new Exception(msg, ex);
newEx.Source = src;
It's just easier for copy/paste inheritance and code generation.
I'm in a situation now where I have a stream of XML coming in over the wire and I need to instantiate an Entity object that will populate itself from elements in the stream. It's easier to use reflection to figure out which Entity object can handle which XML element than to write a gigantic, maintenance-nightmare conditional statement. There's clearly a dependency between the XML schema and how I structure and name my objects, but I control both so it's not a big problem.
There are lot's of times you want to dynamically instantiate and work with objects where the type isn't known until runtime. For example with OR-mappers or in a plugin architecture. Mocking frameworks use it, if you want to write a logging-library and dynamically want to examine type and properties of exceptions.
If I think a bit longer I can probably come up with more examples.
I find reflection very useful if the input data (like xml) has a complex structure which is easily mapped to object-instances or i need some kind of "is a" relationship between the instances.
As reflection is relatively easy in java, I sometimes use it for simple data (key-value maps) where I have a small fixed set of keys. One one hand it's simple to determine if a key is valid (if the class has a setter setKey(String data)), on the other hand i can change the type of the (textual) input data and hide the transformation (e.g simple cast to int in getKey()), so the rest of the application can rely on correctly typed data.
If the type of some key-value-pair changes for one object (e.g. form int to float), i only have to change it in the data-object and its users but don't have to keep in mind to check the parser too. This might not be a sensible approach, if performance is an issue...
Writing dispatchers. Twisted uses python's reflective capabilities to dispatch XML-RPC and SOAP calls. RMI uses Java's reflection api for dispatch.
Command line parsing. Building up a config object based on the command line parameters that are passed in.
When writing unit tests, it can be helpful to use reflection, though mostly I've used this to bypass access modifiers (Java).
I've used reflection in C# when there was some internal or private method in the framework or a third party library that I wanted to access.
(Disclaimer: It's not necessarily a best-practice because private and internal methods may be changed in later versions. But it worked for what I needed.)
Well, in statically-typed languages, you'd want to use reflection any time you need to do something "dynamic". It comes in handy for tooling purposes (scanning the members of an object). In Java it's used in JMX and dynamic proxies quite a bit. And there are tons of one-off cases where it's really the only way to go (pretty much anytime you need to do something the compiler won't let you do).
I generally use reflection for debugging. Reflection can more easily and more accurately display the objects within the system than an assortment of print statements. In many languages that have first-class functions, you can even invoke the functions of the object without writing special code.
There is, however, a way to do what you want(ed). Use a hashtable. Store the fields keyed against the field name.
If you really wanted to, you could then create standard Get/Set functions, or create macros that do it on the fly. #define GetX() Get("X") sort of thing.
You could even implement your own imperfect reflection that way.
For the advanced user, if you can compile the code, it may be possible to enable debug output generation and use that to perform reflection.