Errai 3.0.1-SNAPSHOT

org.jboss.errai.codegen
Interface InterningCallback


public interface InterningCallback

An InternCallback can be registered with Context.addInterningCallback(InterningCallback).

Some care should be taken in implementing a callback considering the recursive nature of code generation within the framework. For instance, the following code will produce undesirable results: {code} new InterningCallback() { public Statement intern(LiteralValue<?> literalValue) { if (literalValue instanceof StringLiteral) { final String varName = "stringLiteral_" + literalValue.getValue().hashCode(); getClassBuilder().publicField(varName, String.class) .initializesWith(literalValue.getValue()); return Refs.get(varName); } return null; } } {code} On the surface, the above seems like a reasonable enough implementation. But there is a recursion problem hidden in it. Because we initialize the field with the string value in the default manner, the value will be obtained from the LiteralFactory in the regular manner, and the interned value will reference itself!

You'll end up with code which looks like this: {code} stringLiteral_382389210 = stringLiteral_382389210; {code} ... And it's fair to say the compiler will not like this.

Instead, you should create non-recursive constructs. We can fix the above code like so: {code} new InterningCallback() { public Statement intern(final LiteralValue<?> literalValue) { if (literalValue instanceof StringLiteral) { final String varName = "stringLiteral_" + literalValue.getValue().hashCode(); getClassBuilder().publicField(varName, String.class) .initializesWith( new Statement() { public String generate(Context context) { return new StringLiteral(literalValue.getValue()).getCanonicalString(context); } public MetaClass getType() { return literalValue.getType(); } } ); return Refs.get(varName); } return null; } } {code}

Author:
Mike Brock

Method Summary
 Statement intern(LiteralValue<?> literalValue)
          Intern the supplied LiteralValue.
 

Method Detail

intern

Statement intern(LiteralValue<?> literalValue)
Intern the supplied LiteralValue. This interface allows you to implement an interning strategy for literal values within the code generator framework. For instance, having literalized annotations render to a final field within a generated class with all subsequent references to matching annotations reference that field.

Parameters:
literalValue - the literal value to intern.
Returns:
If this method returns a non-null reference,the generator will assume this value is interned and will use the returned Statement for this literal in all future code generation.

Errai 3.0.1-SNAPSHOT

Copyright © 2013-2014 JBoss, a division of Red Hat. All Rights Reserved.