Static method call on inheritance

108 views
Skip to first unread message

Alexander Popov

unread,
Jun 27, 2016, 7:41:40 PM6/27/16
to Haxe
Hi!

How can I get this class in static method? Class of child in parent static method.


Thanks.

Mark Knol

unread,
Jun 28, 2016, 5:03:52 PM6/28/16
to Haxe
You cannot acces 'this' in a static method. Because 'this' refers to a instance and statics are global so to say.

So either you have to pass an instance of the class to your method, or you have to remove the 'static' keyword.

Alexander Popov

unread,
Jun 28, 2016, 8:44:07 PM6/28/16
to Haxe
Okay, another example: https://gist.github.com/AlexWayfer/7848b5560119fda01aac3999a4bf624b

So, I can not do one of these in Haxe?

Anton Nesterov

unread,
Jun 29, 2016, 3:25:17 AM6/29/16
to Haxe
You're approaching the problem from a wrong angle. Static variables are only existing in a class that's declaring them, they aren't accessable from other classes. What you really need is build macro (haxe unique feature).

In some other languages you can find functionality called "mixin". Haxe doesn't have that out of the box, but you can add it with @:autoBuild macro. In your parent class you want to create a macro method, that will be called at compile time for every child class. Then this macro adds a method you need into every child class.

Now some code:

TestMacro.hx file first:
import haxe.macro.Context;
import haxe.macro.Expr;

class TestMacro {
    macro
static public function build_some_method() : Array<Field> {
       
var fields = Context.getBuildFields();
       
       
// you can't generate methods, but you can generate class
       
// and copy it's method to destination class
       
var c = macro class X {
           
static public function some_method() {
               
return Animal.some_method_internal(some_var);
           
}
       
};
       
// extract method we want
       
var m = Lambda.find(c.fields, function(f) return f.name == "some_method");
       
// insert into target class
        fields
.push(m);
       
// return modified field set
       
return fields;
   
}
}

And then is your animals source code:
@:autoBuild(TestMacro.build_some_method()) //<< invoke macro for child classes
class Animal {

...

 
static private function some_method_internal(value : String) { //<< changed to internal private method with parameter passed from macro generated fn
   
// some needed magic
 
}

...  



среда, 29 июня 2016 г., 3:44:07 UTC+3 пользователь Alexander Popov написал:
Reply all
Reply to author
Forward
0 new messages