/** * Generates something like <code>field = newValue</code> * * @param fieldName * @param valueName * @return */ private static BlockStmt fieldAssignment(String fieldName, String valueName) { BlockStmt body = new BlockStmt(); body.addStatement( new ExpressionStmt(new AssignExpr(new NameExpr(fieldName), new NameExpr(valueName), Operator.ASSIGN))); return body; }
/** * Generates something like <code>field = newValue</code> * * @param fieldName * @param valueName * @return */ private static BlockStmt fieldAssignment(String fieldName, String valueName) { BlockStmt body = new BlockStmt(); body.addStatement( new ExpressionStmt(new AssignExpr(new NameExpr(fieldName), new NameExpr(valueName), Operator.ASSIGN))); return body; }
public static void main(String[] args) throws FileNotFoundException { // The directory where we store the examples String pathToExamplesDir = "." + separator + "src" + separator + "main" + separator + "resources"; // Parse the code of an entire source file, a.k.a. a Compilation Unit CompilationUnit compilationUnitNode = JavaParser.parse(new File(pathToExamplesDir + separator + "ASimpleClass.java")); printCompilationUnit("My original class", compilationUnitNode); // Modifying the name of the class compilationUnitNode.getClassByName("ASimpleClass").get() .setName("MyRenamedClass"); printCompilationUnit("Renamed class", compilationUnitNode); // Adding a method: we add a setter MethodDeclaration setter = compilationUnitNode .getClassByName("MyRenamedClass").get() .addMethod("setAField", Modifier.PUBLIC); setter.addParameter("boolean", "aField"); setter.getBody().get().getStatements().add(new ExpressionStmt( new AssignExpr( new FieldAccessExpr(new ThisExpr(),"aField"), new NameExpr("aField"), AssignExpr.Operator.ASSIGN ))); printCompilationUnit("With a setter", compilationUnitNode); } }
@Override public AssignExpr doMerge(AssignExpr first, AssignExpr second) { AssignExpr ae = new AssignExpr(); ae.setOperator(first.getOperator()); ae.setTarget(mergeSingle(first.getTarget(),second.getTarget())); ae.setValue(mergeSingle(first.getValue(),second.getValue())); return ae; }
private MethodDeclaration setterDeclaration(EntityField field) { MethodDeclaration decl = new MethodDeclaration(ModifierSet.PUBLIC, new VoidType(), "set" + CaseConverter.pascalCase(field.getName()), Collections.singletonList(new Parameter( ASTHelper.createReferenceType(field.getType().getSimpleName(), 0), new VariableDeclaratorId(field.getName())))); BlockStmt body = new BlockStmt(); body.setStmts( Collections.singletonList( new ExpressionStmt( new AssignExpr( new FieldAccessExpr(new ThisExpr(), field.getName()), ASTHelper.createNameExpr(field.getName()), AssignExpr.Operator.assign )))); decl.setBody(body); return decl; }