groovy-users mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From John Smiljanic <>
Subject Re: Adding a Trait to a ClassNode during semantic analysis
Date Thu, 21 Apr 2016 21:16:16 GMT
After some digging I found
org.codehaus.groovy.transform.trait.TraitComposer and from there I was able
to backtrack to how groovy transforms statically defined traits.  This is
performed in canonalization, so it appears that a trait that is added to a
class during semantic analysis may still have its fields/behavior applied
to that class.  So, I was able to get this to work as follows:

1.  Compile the trait.

I was having some problems jointly compiling the trait while compiling the
class that implements the trait when using the embedded compiler.  If I
recall correctly the base issue was that if I declared the trait as follows:

            classNode.addInterface(new ClassNode(
               <trait name>
               , Opcodes.ACC_INTERFACE
               , ClassHelper.make(Object.class)));

the TraitComposer did not recognize the interface ClassNode as a Trait (no
@Trait annotation).  I suppose that the ClassNode constructor above does
not trigger a proper compilation/load of my trait's groovy file (?), but I
frankly didn't dig much deeper.

This is fine for my purposes.  In my case, the Trait developer (framework
developer)  is different than the class developer (citizen developer).

2.  Declare the trait during semantic analysis of the Class.

classNode.addInterface(new ClassNode(<trait javaclass from 1>);

On Wed, Apr 20, 2016 at 3:08 PM, John Smiljanic <>

> Hi All,
> Groovy 2.3.7.
> I've been experimenting with trying to add a Trait (or Mixin) to a
> ClassNode during semantic analysis (compiler phase).  I've tried using
> ClassNode::addInterface and ClassNode::addMixin passing the appropriate.  I
> sort of expected ClassNode to have an addTrait or something like.
> Is setting a trait at this phase of compilation supported?
> JR

View raw message