reflection - How can I get the name of the defined class in a parent static method in Groovy -
note: found answer suggests java redirect static method call it's own class if it's called on child class guess need find groovy work-around trick or it's not going doable.
here's problem: created abstract generic "launcher" class "public static void main". idea extend , in child class annotate methods this:
@command("show explorere shell") public dir() { "explorer".execute() } the parent of class has main goes through, reflects @command annotation , if method name matches parameter, executes it.
the problem can't figure out how tell actual, instantiated class within parent's static main method.
i'm pretty sure there trick somewhere--"this" won't work in statics, stack traces don't contain actual class, parent class, , can't find meta-info in class or metaclass objects helps.
currently i've gotten work hard-coding name of child class parent's main this:
public class quickcli { public static void main(string[] args} { (new hardcodedchildclassname())."${args[0]}"() } } i cut quite bit out of that, it's general idea. i'd replace
"new hardcodedchildclassname()" with work class extends class.
given 2 code snips above, command executed command line as:
groovy hardcodedchildclassname dir although i'd prefer not make @command methods static if had to, i'm not convinced make work.
i'm not sure that's possible. in case, it's ugly hack if is. i'd suggest alternative: rather using static main() entry point, make quickcli runnable. groovy automatically create instance , call run() on when launched.
one minor problem here capturing command-line arguments. groovy handles passing them constructor string[] parameter. instantiated class needs constructor capture args, in java, constructors not inherited. fortunately, groovy has inheritconstructors annotation works around this.
here's example of how look:
class quickcli implements runnable { def args quickcli(string[] args) { this.args = args } void run() { "${args[0]}"() } } @groovy.transform.inheritconstructors class hardcodedchildclassname extends quickcli { @command("show explorere shell") public dir() { "explorer".execute() } }
Comments
Post a Comment