Another user chimed in on SO and provided this answer that appears to work
in all test scenarios, even nested template scenarios:

String basic = "<%" +
            " def mc1=testInstance.&test;" +
            "println \"mc1 class ${mc1.getClass()}\";" +
            "println \"mc1 metaclass ${mc1.getMetaClass()}\";" +
            "println mc1.getClass();" +
            "mc1();" +
            "mc1('var1');" +
            "mc1('var1', 'var2');" +
            "testMethod();" +
            "testMethod('var1');" +
            " %>";

    TemplateEngine engine = new GStringTemplateEngine();

    TestMethodClass instance = new TestMethodClass();

    // Prepare binding map
    Map<String, Object> bindings = new HashMap<>();
    bindings.put("testInstance", instance);

    Template t = engine.createTemplate(basic);

    Closure<?> make = (Closure<?>) t.make(bindings); // cast as closure

    int resolveStrategy = make.getResolveStrategy();
    make.setResolveStrategy(Closure.OWNER_FIRST);

    // set method closure which you want to invoke directly (without .
    // notation). This is more or less same what you pass via binding map
    // but too verbose. You can encapsulate this inside a nice static
    // method
    InvokerHelper.setProperty(make.getOwner(), "testMethod", new
MethodClosure(instance, "test"));

    make.setResolveStrategy(resolveStrategy);
    String result = make.toString();


On Mon, Feb 13, 2017 at 3:14 AM, Alessio Stalla <[email protected]>
wrote:

> I answered: http://stackoverflow.com/a/42202684/296025
> But that won't solve your problem, I'm afraid.
>
> On 13 February 2017 at 08:03, OmniTrade <[email protected]> wrote:
>
>> Hi All,
>>
>> I won't bore you with the gritty details here since they are already well
>> described on StackOverflow.
>>
>> It seems that few people have the chops to tackle this question. It
>> sounds solvable and maybe some of the pros here can attempt it.
>>
>> http://stackoverflow.com/questions/41196600/how-do-i-bind-al
>> l-methods-of-a-certain-name-in-an-object-into-a-template-via-the
>>
>> Rumour has it that there is also a 500 point reward for the canonical
>> answer.
>>
>> Good Luck.
>>
>
>

Reply via email to