本文整理匯總了Java中com.sun.source.tree.MethodTree.getBody方法的典型用法代碼示例。如果您正苦於以下問題:Java MethodTree.getBody方法的具體用法?Java MethodTree.getBody怎麽用?Java MethodTree.getBody使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類com.sun.source.tree.MethodTree
的用法示例。
在下文中一共展示了MethodTree.getBody方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。
示例1: performRewriteToMemberReference
import com.sun.source.tree.MethodTree; //導入方法依賴的package包/類
public void performRewriteToMemberReference() {
MethodTree methodTree = getMethodFromFunctionalInterface(newClassTree);
if (methodTree.getBody() == null || methodTree.getBody().getStatements().size() != 1)
return;
Tree tree = methodTree.getBody().getStatements().get(0);
if (tree.getKind() == Tree.Kind.EXPRESSION_STATEMENT) {
tree = ((ExpressionStatementTree)tree).getExpression();
} else if (tree.getKind() == Tree.Kind.RETURN) {
tree = ((ReturnTree)tree).getExpression();
} else {
return;
}
Tree changed = null;
if (tree.getKind() == Tree.Kind.METHOD_INVOCATION) {
changed = methodInvocationToMemberReference(copy, tree, pathToNewClassTree, methodTree.getParameters(),
preconditionChecker.needsCastToExpectedType());
} else if (tree.getKind() == Tree.Kind.NEW_CLASS) {
changed = newClassToConstructorReference(copy, tree, pathToNewClassTree, methodTree.getParameters(), preconditionChecker.needsCastToExpectedType());
}
if (changed != null) {
copy.rewrite(newClassTree, changed);
}
}
示例2: getLambdaBody
import com.sun.source.tree.MethodTree; //導入方法依賴的package包/類
private Tree getLambdaBody(MethodTree methodTree, WorkingCopy copy) {
if (methodTree.getBody() == null) {
return null;
}
TreePath pathToMethodBody = TreePath.getPath(pathToNewClassTree, methodTree.getBody());
//if body is just a return statement, the lambda body should omit the block and return keyword
Pattern pattern = PatternCompiler.compile(copy, "{ return $expression; }",
Collections.<String, TypeMirror>emptyMap(), Collections.<String>emptyList());
Collection<? extends Occurrence> matches = Matcher.create(copy)
.setSearchRoot(pathToMethodBody)
.setTreeTopSearch()
.match(pattern);
if (matches.isEmpty()) {
return methodTree.getBody();
}
return matches.iterator().next().getVariables().get("$expression").getLeaf();
}
示例3: constructorInvokesAnother
import com.sun.source.tree.MethodTree; //導入方法依賴的package包/類
/** does the constructor invoke another constructor in the same class via this(...)? */
private boolean constructorInvokesAnother(MethodTree constructor, VisitorState state) {
BlockTree body = constructor.getBody();
List<? extends StatementTree> statements = body.getStatements();
if (statements.size() > 0) {
StatementTree statementTree = statements.get(0);
if (isThisCall(statementTree, state)) {
return true;
}
}
return false;
}
示例4: prepareStandardTest
import com.sun.source.tree.MethodTree; //導入方法依賴的package包/類
private void prepareStandardTest(String className, String methodName) throws Exception {
if (methodName == null) {
methodName = getName();
methodName = Character.toLowerCase(methodName.charAt(4)) +
methodName.substring(5);
}
prepareFileTest(false, "Test.java", "Base.java");
String pn = getMyPackageName();
TypeElement tel = info.getElements().getTypeElement(pn + "." + className);
for (ExecutableElement e : ElementFilter.methodsIn(tel.getEnclosedElements())) {
if (e.getSimpleName().contentEquals(methodName)) {
testMethod = e;
MethodTree mt = (MethodTree)info.getTrees().getTree(testMethod);
testMethodTree = mt;
List<? extends StatementTree> stmts = mt.getBody().getStatements();
Tree t = stmts.get(0);
if (t.getKind() == Tree.Kind.RETURN) {
t = ((ReturnTree)t).getExpression();
} else if (stmts.size() > 1) {
t = mt.getBody();
}
this.expressionTree = t;
return;
}
}
fail("Testcase method source not found");
}
示例5: notAssignedInAnyInitializer
import com.sun.source.tree.MethodTree; //導入方法依賴的package包/類
/**
* @param entities relevant entities from class
* @param notInitializedInConstructors those fields not initialized in some constructor
* @param state
* @return those fields from notInitializedInConstructors that are not initialized in any
* initializer method
*/
private Set<Symbol> notAssignedInAnyInitializer(
FieldInitEntities entities, Set<Symbol> notInitializedInConstructors, VisitorState state) {
Trees trees = Trees.instance(JavacProcessingEnvironment.instance(state.context));
Symbol.ClassSymbol classSymbol = entities.classSymbol();
Set<Element> initInSomeInitializer = new LinkedHashSet<>();
for (MethodTree initMethodTree : entities.instanceInitializerMethods()) {
if (initMethodTree.getBody() == null) {
continue;
}
addInitializedFieldsForBlock(
state,
trees,
classSymbol,
initInSomeInitializer,
initMethodTree.getBody(),
new TreePath(state.getPath(), initMethodTree));
}
for (BlockTree block : entities.instanceInitializerBlocks()) {
addInitializedFieldsForBlock(
state,
trees,
classSymbol,
initInSomeInitializer,
block,
new TreePath(state.getPath(), block));
}
Set<Symbol> result = new LinkedHashSet<>();
for (Symbol fieldSymbol : notInitializedInConstructors) {
if (!initInSomeInitializer.contains(fieldSymbol)) {
result.add(fieldSymbol);
}
}
return result;
}
示例6: noopMethodInAbstractClass
import com.sun.source.tree.MethodTree; //導入方法依賴的package包/類
@Hint(displayName = "#DN_org.netbeans.modules.java.hints.ClassStructure.noopMethodInAbstractClass", description = "#DESC_org.netbeans.modules.java.hints.ClassStructure.noopMethodInAbstractClass", category = "class_structure", enabled = false, suppressWarnings = {"NoopMethodInAbstractClass"}, options=Options.QUERY) //NOI18N
@TriggerTreeKind(Kind.METHOD)
public static ErrorDescription noopMethodInAbstractClass(HintContext context) {
final MethodTree mth = (MethodTree) context.getPath().getLeaf();
final Tree parent = context.getPath().getParentPath().getLeaf();
if (TreeUtilities.CLASS_TREE_KINDS.contains(parent.getKind()) && ((ClassTree) parent).getModifiers().getFlags().contains(Modifier.ABSTRACT)) {
final BlockTree body = mth.getBody();
if (body != null && body.getStatements().isEmpty()) {
return ErrorDescriptionFactory.forName(context, mth, NbBundle.getMessage(ClassStructure.class, "MSG_NoopMethodInAbstractClass", mth.getName())); //NOI18N
}
}
return null;
}
示例7: reflowMethodBody
import com.sun.source.tree.MethodTree; //導入方法依賴的package包/類
public BlockTree reflowMethodBody(CompilationUnitTree topLevel, ClassTree ownerClass, MethodTree methodToReparse) {
Flow flow = Flow.instance(context);
TreeMaker make = TreeMaker.instance(context);
flow.reanalyzeMethod(make.forToplevel((JCCompilationUnit)topLevel),
(JCClassDecl)ownerClass);
return methodToReparse.getBody();
}
示例8: doModification
import com.sun.source.tree.MethodTree; //導入方法依賴的package包/類
protected void doModification(ResultIterator resultIterator) throws Exception {
WorkingCopy copy = WorkingCopy.get(resultIterator.getParserResult());
copy.toPhase(Phase.RESOLVED);
CompilationUnitTree cut = copy.getCompilationUnit();
ClassTree ct = (ClassTree) cut.getTypeDecls().get(0);
MethodTree mt = (MethodTree) ct.getMembers().get(1);
TreeMaker treeMaker = copy.getTreeMaker();
BlockTree bt = mt.getBody();
StatementTree stmt = treeMaker.Variable(treeMaker.Modifiers(EnumSet.noneOf(Modifier.class)), "is", treeMaker.QualIdent("java.io.InputStream"), treeMaker.Literal(null)); //NOI18N
bt = treeMaker.addBlockStatement(bt, stmt);
BlockTree tryBlock = treeMaker.Block(Collections.<StatementTree>emptyList(), false);
ExpressionTree et = treeMaker.NewClass(null, Collections.<ExpressionTree>emptyList(), treeMaker.QualIdent("java.io.File"), Collections.singletonList(treeMaker.Literal("test.txt")), null); //NOI18N
stmt = treeMaker.Variable(treeMaker.Modifiers(EnumSet.noneOf(Modifier.class)), "f", treeMaker.QualIdent("java.io.File"), et); //NOI18N
tryBlock = treeMaker.addBlockStatement(tryBlock, stmt);
et = treeMaker.NewClass(null, Collections.<ExpressionTree>emptyList(), treeMaker.QualIdent("java.io.FileInputStream"), Collections.singletonList(treeMaker.Identifier("f")), null); //NOI18N
et = treeMaker.Assignment(treeMaker.Identifier("is"), et); //NOI18N
tryBlock = treeMaker.addBlockStatement(tryBlock, treeMaker.ExpressionStatement(et));
et = treeMaker.MemberSelect(treeMaker.Identifier("is"), "read"); //NOI18N
et = treeMaker.MethodInvocation(Collections.<ExpressionTree>emptyList(), et, Collections.<ExpressionTree>emptyList());
stmt = treeMaker.Try(treeMaker.Block(Collections.singletonList(treeMaker.ExpressionStatement(et)), false), Collections.<CatchTree>emptyList(), null);
et = treeMaker.MethodInvocation(Collections.<ExpressionTree>emptyList(), treeMaker.MemberSelect(treeMaker.QualIdent("java.util.logging.Logger"), "getLogger"), Collections.<ExpressionTree>emptyList()); //NOI18N
et = treeMaker.addMethodInvocationArgument((MethodInvocationTree) et, treeMaker.MethodInvocation(Collections.<ExpressionTree>emptyList(), treeMaker.MemberSelect(treeMaker.MemberSelect(treeMaker.QualIdent("org.netbeans.samples.ClassA"), "class"), "getName"), Collections.<ExpressionTree>emptyList())); //NOI18N
et = treeMaker.MethodInvocation(Collections.<ExpressionTree>emptyList(), treeMaker.MemberSelect(et, "log"), Collections.<ExpressionTree>emptyList()); //NOI18N
et = treeMaker.addMethodInvocationArgument((MethodInvocationTree) et, treeMaker.MemberSelect(treeMaker.QualIdent("java.util.logging.Logger"), "SEVERE")); //NOI18N
et = treeMaker.addMethodInvocationArgument((MethodInvocationTree) et, treeMaker.Literal(null));
et = treeMaker.addMethodInvocationArgument((MethodInvocationTree) et, treeMaker.Identifier("ex")); //NOI18N
BlockTree catchBlock = treeMaker.Block(Collections.singletonList(treeMaker.ExpressionStatement(et)), false);
stmt = treeMaker.addTryCatch((TryTree) stmt, treeMaker.Catch(treeMaker.Variable(treeMaker.Modifiers(EnumSet.noneOf(Modifier.class)), "ex", treeMaker.QualIdent("java.io.IOException"), null), catchBlock)); //NOI18N
tryBlock = treeMaker.addBlockStatement(tryBlock, stmt);
et = treeMaker.MemberSelect(treeMaker.Identifier("is"), "close"); //NOI18N
et = treeMaker.MethodInvocation(Collections.<ExpressionTree>emptyList(), et, Collections.<ExpressionTree>emptyList());
stmt = treeMaker.Try(treeMaker.Block(Collections.singletonList(treeMaker.ExpressionStatement(et)), false), Collections.<CatchTree>emptyList(), null);
stmt = treeMaker.addTryCatch((TryTree) stmt, treeMaker.Catch(treeMaker.Variable(treeMaker.Modifiers(EnumSet.noneOf(Modifier.class)), "ex", treeMaker.QualIdent("java.io.IOException"), null), catchBlock)); //NOI18N
stmt = treeMaker.Try(tryBlock, Collections.<CatchTree>emptyList(), treeMaker.Block(Collections.singletonList(stmt), false));
stmt = treeMaker.addTryCatch((TryTree) stmt, treeMaker.Catch(treeMaker.Variable(treeMaker.Modifiers(EnumSet.noneOf(Modifier.class)), "ex", treeMaker.QualIdent("java.io.FileNotFoundException"), null), catchBlock)); //NOI18N
bt = treeMaker.addBlockStatement(bt, stmt);
copy.rewrite(mt.getBody(), bt);
}
示例9: testRewriteMultipleExpressions
import com.sun.source.tree.MethodTree; //導入方法依賴的package包/類
@Test
public void testRewriteMultipleExpressions() throws Exception {
File testFile = new File(getWorkDir(), "Test.java");
TestUtilities.copyStringToFile(testFile,
"\n" +
"public class MultipleExpressionsTest {\n" +
" public void testMethod() {\n" +
" printGreeting();\n" +
" printGreeting();\n" +
" printGreeting();\n" +
" }\n" +
" public void printGreeting() {\n" +
" System.out.println(\"Hello World!\");\n" +
" }\n" +
"}\n");
String golden = "\n" +
"public class MultipleExpressionsTest {\n" +
" public void testMethod() {\n" +
" System.out.println(\"Hello World!\");\n" +
" System.out.println(\"Hello World!\");\n" +
" System.out.println(\"Hello World!\");\n" +
" }\n" +
" public void printGreeting() {\n" +
" System.out.println(\"Hello World!\");\n" +
" }\n" +
"}\n";
JavaSource src = getJavaSource(testFile);
Task<WorkingCopy> task = new Task<WorkingCopy>() {
public void run(WorkingCopy workingCopy) throws Exception {
workingCopy.toPhase(JavaSource.Phase.RESOLVED);
CompilationUnitTree cut = workingCopy.getCompilationUnit();
TreeMaker make = workingCopy.getTreeMaker();
List<? extends Tree> classes = cut.getTypeDecls();
ClassTree clazz = (ClassTree) classes.get(0);
List<? extends Tree> trees = clazz.getMembers();
MethodTree testMethod = (MethodTree) trees.get(1);
BlockTree body = testMethod.getBody();
MethodTree printMethod = (MethodTree) trees.get(2);
BlockTree printBody = printMethod.getBody();
List<StatementTree> statements = new LinkedList<StatementTree>();
statements.add(printBody.getStatements().get(0));
statements.add(printBody.getStatements().get(0));
statements.add(printBody.getStatements().get(0));
BlockTree modified = make.Block(statements, false);
workingCopy.rewrite(body, modified);
}
};
src.runModificationTask(task).commit();
String res = TestUtilities.copyFileToString(testFile);
System.out.println(res);
assertEquals(golden, res);
}
示例10: testChangeToFinalLocVar
import com.sun.source.tree.MethodTree; //導入方法依賴的package包/類
/**
* Tests the change of modifier in local variable
*/
public void testChangeToFinalLocVar() throws Exception {
testFile = new File(getWorkDir(), "Test.java");
TestUtilities.copyStringToFile(testFile,
"package hierbas.del.litoral;\n\n" +
"import java.io.*;\n\n" +
"public class Test {\n" +
" public void taragui() {\n" +
" int i = 10;\n" +
" }\n" +
"}\n"
);
String golden =
"package hierbas.del.litoral;\n\n" +
"import java.io.*;\n\n" +
"public class Test {\n" +
" public void taragui() {\n" +
" final int i = 10;\n" +
" }\n" +
"}\n";
JavaSource testSource = JavaSource.forFileObject(FileUtil.toFileObject(testFile));
Task<WorkingCopy> task = new Task<WorkingCopy>() {
public void run(WorkingCopy workingCopy) throws java.io.IOException {
workingCopy.toPhase(Phase.RESOLVED);
TreeMaker make = workingCopy.getTreeMaker();
// finally, find the correct body and rewrite it.
ClassTree clazz = (ClassTree) workingCopy.getCompilationUnit().getTypeDecls().get(0);
MethodTree method = (MethodTree) clazz.getMembers().get(1);
BlockTree block = method.getBody();
VariableTree vt = (VariableTree) block.getStatements().get(0);
ModifiersTree mods = vt.getModifiers();
workingCopy.rewrite(mods, make.Modifiers(Collections.<Modifier>singleton(Modifier.FINAL)));
}
};
testSource.runModificationTask(task).commit();
String res = TestUtilities.copyFileToString(testFile);
System.err.println(res);
assertEquals(golden, res);
}
示例11: testModifyingIf
import com.sun.source.tree.MethodTree; //導入方法依賴的package包/類
public void testModifyingIf() throws Exception {
testFile = new File(getWorkDir(), "Test.java");
TestUtilities.copyStringToFile(testFile,
"package personal;\n" +
"\n" +
"public class Test {\n" +
" public boolean method(int i) {\n" +
" int y = 0;\n" +
" if (i == 0) {\n" +
" y = 2;\n" +
" } else {y = 9;}\n" +
" return y == 8;\n" +
" }\n" +
"}\n");
String golden =
"package personal;\n" +
"\n" +
"public class Test {\n" +
" public boolean method(int i) {\n" +
" int y = 0;\n" +
" if (method(null)) {\n" +
" return true;\n" +
" }\n" +
" return y == 8;\n" +
" }\n" +
"}\n";
JavaSource src = getJavaSource(testFile);
Task<WorkingCopy> task = new Task<WorkingCopy>() {
public void run(WorkingCopy workingCopy) throws IOException {
workingCopy.toPhase(Phase.RESOLVED);
TreeMaker make = workingCopy.getTreeMaker();
ClassTree clazz = (ClassTree) workingCopy.getCompilationUnit().getTypeDecls().get(0);
MethodTree method = (MethodTree) clazz.getMembers().get(1);
BlockTree block = method.getBody();
IfTree mit = (IfTree) block.getStatements().get(1);
IfTree nue = make.If(
make.Parenthesized(make.MethodInvocation(
Collections.<ExpressionTree>emptyList(),
make.Identifier("method"),
Arrays.asList(make.Literal(null)))
),
make.Block(
Collections.<StatementTree>singletonList(make.Return(make.Literal(true))),
false
),
null
);
workingCopy.rewrite(mit, nue);
}
public void cancel() {
}
};
src.runModificationTask(task).commit();
String res = TestUtilities.copyFileToString(testFile);
System.err.println(res);
assertEquals(golden, res);
}
示例12: test158463b
import com.sun.source.tree.MethodTree; //導入方法依賴的package包/類
public void test158463b() throws Exception {
testFile = new File(getWorkDir(), "Test.java");
TestUtilities.copyStringToFile(testFile,
"package personal;\n" +
"\n" +
"public class Test {\n" +
" void m1(int p, int q) {\n" +
" if (p > 0)\n" +
" if (q > 0) p++; \n" +
" else p--;\n" +
" }\n" +
"}\n");
String golden =
"package personal;\n" +
"\n" +
"public class Test {\n" +
" void m1(int p, int q) {\n" +
" if ((p > 0) && (q > 0))\n" +
" p++;\n" +
" else {\n" + //TODO: brackets (#158154)
" p--;\n" +
" }\n" +
" }\n" +
"}\n";
JavaSource src = getJavaSource(testFile);
Task<WorkingCopy> task = new Task<WorkingCopy>() {
public void run(WorkingCopy workingCopy) throws IOException {
workingCopy.toPhase(Phase.RESOLVED);
TreeMaker make = workingCopy.getTreeMaker();
ClassTree clazz = (ClassTree) workingCopy.getCompilationUnit().getTypeDecls().get(0);
MethodTree method = (MethodTree) clazz.getMembers().get(1);
BlockTree block = method.getBody();
IfTree original = (IfTree) block.getStatements().get(0);
IfTree original2 = (IfTree) original.getThenStatement();
IfTree modified = make.If(
make.Parenthesized(
make.Binary(Kind.CONDITIONAL_AND,
original.getCondition(),
original2.getCondition())),
original2.getThenStatement(),
original2.getElseStatement());
workingCopy.rewrite(original, modified);
}
public void cancel() {
}
};
src.runModificationTask(task).commit();
String res = TestUtilities.copyFileToString(testFile);
System.err.println(res);
assertEquals(golden, res);
}
示例13: testFile
import com.sun.source.tree.MethodTree; //導入方法依賴的package包/類
@Test(dataProvider = "crawler")
public void testFile(String fileName) throws IOException {
File file = getSourceFile(fileName);
final JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
final StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);
boolean success = true;
StringWriter writer = new StringWriter();
writer.write("Testing : " + file.toString() + "\n");
String text = new String(Files.readAllBytes(file.toPath()), StandardCharsets.UTF_8);
Iterable<? extends JavaFileObject> compilationUnits = fileManager.getJavaFileObjects(file);
JavacTaskImpl task = (JavacTaskImpl) compiler.getTask(null, fileManager, null, null, null, compilationUnits);
Iterable<? extends CompilationUnitTree> asts = task.parse();
Trees trees = Trees.instance(task);
SourcePositions sp = trees.getSourcePositions();
for (CompilationUnitTree cut : asts) {
for (ImportTree imp : cut.getImports()) {
success &= testStatement(writer, sp, text, cut, imp);
}
for (Tree decl : cut.getTypeDecls()) {
success &= testStatement(writer, sp, text, cut, decl);
if (decl instanceof ClassTree) {
ClassTree ct = (ClassTree) decl;
for (Tree mem : ct.getMembers()) {
if (mem instanceof MethodTree) {
MethodTree mt = (MethodTree) mem;
BlockTree bt = mt.getBody();
// No abstract methods or constructors
if (bt != null && mt.getReturnType() != null) {
// The modifiers synchronized, abstract, and default are not allowed on
// top-level declarations and are errors.
Set<Modifier> modifier = mt.getModifiers().getFlags();
if (!modifier.contains(Modifier.ABSTRACT)
&& !modifier.contains(Modifier.SYNCHRONIZED)
&& !modifier.contains(Modifier.DEFAULT)) {
success &= testStatement(writer, sp, text, cut, mt);
}
testBlock(writer, sp, text, cut, bt);
}
}
}
}
}
}
fileManager.close();
if (!success) {
throw new AssertionError(writer.toString());
}
}
示例14: test257910NestedIfs
import com.sun.source.tree.MethodTree; //導入方法依賴的package包/類
public void test257910NestedIfs() throws Exception {
String source = "public class Test {\n"
+ " public void test() {\n"
+ " if (true) {\n"
+ " System.out.println(2);\n"
+ " } else if (false) {\n"
+ " System.out.println(1);\n"
+ " }\n"
+ " }\n"
+ "}";
String golden = "public class Test {\n"
+ " public void test() {\n"
+ " if (false) {\n"
+ " if (false) {\n"
+ " System.out.println(1);\n"
+ " }\n"
+ " } else {\n"
+ " System.out.println(2);\n"
+ " }\n"
+ " }\n"
+ "}";
testFile = new File(getWorkDir(), "Test.java");
TestUtilities.copyStringToFile(testFile, source);
JavaSource src = getJavaSource(testFile);
Task<WorkingCopy> task = new Task<WorkingCopy>() {
public void run(WorkingCopy copy) throws Exception {
if (copy.toPhase(Phase.RESOLVED).compareTo(Phase.RESOLVED) < 0) {
return;
}
TreeMaker make = copy.getTreeMaker();
ClassTree clazz = (ClassTree) copy.getCompilationUnit().getTypeDecls().get(0);
MethodTree method = (MethodTree) clazz.getMembers().get(1);
BlockTree block = method.getBody();
IfTree originalA = (IfTree) block.getStatements().get(0);
// swap branches
IfTree rewrite = make.If(
make.Parenthesized(
make.Literal(Boolean.FALSE)
),
originalA.getElseStatement(), originalA.getThenStatement()
);
copy.rewrite(originalA, rewrite);
}
};
src.runModificationTask(task).commit();
String res = TestUtilities.copyFileToString(testFile);
System.out.println(res);
assertEquals(golden, res);
}
示例15: test257910NestedIfsCorrectlyPaired
import com.sun.source.tree.MethodTree; //導入方法依賴的package包/類
public void test257910NestedIfsCorrectlyPaired() throws Exception {
String source = "public class Test {\n"
+ " public void test() {\n"
+ " if (true) {\n"
+ " System.out.println(2);\n"
+ " } else if (false) {\n"
+ " System.out.println(1);\n"
+ " } else \n"
+ " System.out.println(3);\n"
+ " }\n"
+ "}";
String golden = "public class Test {\n"
+ " public void test() {\n"
+ " if (false) if (false) {\n"
+ " System.out.println(1);\n"
+ " } else\n"
+ " System.out.println(3); else {\n"
+ " System.out.println(2);\n"
+ " }\n"
+ " }\n"
+ "}";
testFile = new File(getWorkDir(), "Test.java");
TestUtilities.copyStringToFile(testFile, source);
JavaSource src = getJavaSource(testFile);
Task<WorkingCopy> task = new Task<WorkingCopy>() {
public void run(WorkingCopy copy) throws Exception {
if (copy.toPhase(Phase.RESOLVED).compareTo(Phase.RESOLVED) < 0) {
return;
}
TreeMaker make = copy.getTreeMaker();
ClassTree clazz = (ClassTree) copy.getCompilationUnit().getTypeDecls().get(0);
MethodTree method = (MethodTree) clazz.getMembers().get(1);
BlockTree block = method.getBody();
IfTree originalA = (IfTree) block.getStatements().get(0);
// swap branches
IfTree rewrite = make.If(
make.Parenthesized(
make.Literal(Boolean.FALSE)
),
originalA.getElseStatement(), originalA.getThenStatement()
);
copy.rewrite(originalA, rewrite);
}
};
src.runModificationTask(task).commit();
String res = TestUtilities.copyFileToString(testFile);
System.out.println(res);
assertEquals(golden, res);
}