Expert Beginner

Learning by doing

0%

Javac (JC) Cookbook - How to introduce new attribute into exist class

Question

對已經存在的類別加入新的attribute

Answer

作法是透過TreeMaker#VerDef()來產生新的variable的定義,然後透過JCClassDecldefs#prepend()加到類別的Class Tree上。

以下是使用TreeMaker#VerDef()產生serialVersionUID的定義和初始化。

1
2
3
4
5
6
7
private JCTree.JCVariableDecl genSerialVersionUIDVariable() {
JCTree.JCModifiers modifiers = treeMaker.Modifiers(PRIVATE + STATIC + FINAL);
Name id = names.fromString("serialVersionUID");
JCTree.JCExpression varType = treeMaker.Type(new Type.JCPrimitiveType(TypeTag.LONG, null));
JCTree.JCExpression init = treeMaker.Literal(1L);
return treeMaker.VarDef(modifiers, id, varType, init);
}

以下是把VariableTree加到ClassTree的寫法

1
jcClassDecl.defs = jcClassDecl.defs.prepend(genSerialVersionUIDVariable());

這個VariableTree對應的java程式碼如下

1
private static final long serialVersionUID = 1L;

Discussion