HaxeDoc2

(やまだぃちぅ) #1

The problem here is that the compiler never actually “sees” the typehaxe.Template, so it
does not compile it into the output. Furthermore, even if it were to see the type there could be
issues arising from dead code elimitation (8.2) eliminating types or fields which are only used
via reflection.
Another set of problems comes from the fact that, by design, several reflection functions ex-
pect arguments of type Dynamic (2.7), meaning the compiler cannot check if the passed in argu-
ments are correct. The following example demonstrates a common mistake when working with
callMethod:
1 class Main {
2 static function main() {
3 // wrong
4 //Reflect.callMethod(Main, "f", []);
5 // right
6 Reflect.callMethod(Main,
7 Reflect.field(Main, "f"), []);
8 }
9
10 static function f() {
11 trace(’Called’);
12 }
13 }


The commented out call would be accepted by the compiler because it assigns the string"f"
to the function argumentfuncwhich is specified to beDynamic.
A good advice when working with reflection is to wrap it in a few functions within an appli-
cation or API which are called by otherwise type-safe code. An example could look like this:
1 typedef MyStructure ={
2 name: String,
3 score: 12
4 }
5
6 class Main {
7 static function main() {
8 var data = reflective();
9 // At this point data is nicelytyped as
10 // MyStructure
11 }
12
13 static function reflective():MyStructure{
14 // Work with reflection hereto get some
15 // values we want to return.
16 return {
17 name: "Reflection",
18 score:0
19 }
20 }
21 }


While the methodreflectivecould interally work with reflection (andDynamicfor that
matter) a lot, its return value is a typed structure which the callers can use in a type-safe manner.
Free download pdf