下面列出了com.sun.source.tree.MethodTree#getBody ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
private ClassTree moveRestMethod( TreeMaker maker, String movedName,
MethodTree method, WorkingCopy copy, ClassTree classTree)
{
List<? extends VariableTree> parameters = method.getParameters();
Tree returnType = method.getReturnType();
BlockTree body = method.getBody();
ModifiersTree modifiers = maker.Modifiers(EnumSet.of(Modifier.PRIVATE));
MethodTree newMethod = maker.Method(modifiers, movedName,
returnType,
Collections.<TypeParameterTree> emptyList(),
parameters,
Collections.<ExpressionTree> emptyList(),body,null);
ClassTree newClass = maker.addClassMember(classTree, newMethod);
newClass = maker.removeClassMember(newClass, method);
return newClass;
}
public JCTree.JCBlock reparseMethodBody(Context ctx, CompilationUnitTree topLevel, MethodTree methodToReparse, String newBodyText,
final Map<JCTree, Object> docComments) throws IllegalArgumentException, IllegalAccessException {
int startPos = ((JCTree.JCBlock)methodToReparse.getBody()).pos;
char[] body = new char[startPos + newBodyText.length() + 1];
Arrays.fill(body, 0, startPos, ' ');
for (int i = 0; i < newBodyText.length(); i++) {
body[startPos + i] = newBodyText.charAt(i);
}
body[startPos + newBodyText.length()] = '\u0000';
CharBuffer buf = CharBuffer.wrap(body, 0, body.length - 1);
com.sun.tools.javac.parser.JavacParser parser = newParser(ctx, buf, ((JCTree.JCBlock)methodToReparse.getBody()).pos, ((JCTree.JCCompilationUnit)topLevel).endPositions);
final JCTree.JCStatement statement = parser.parseStatement();
if (statement.getKind() == Tree.Kind.BLOCK) {
if (docComments != null) {
docComments.putAll((Map<JCTree, Object>) lazyDocCommentsTable.get(parserDocComments.get(parser)));
}
return (JCTree.JCBlock) statement;
}
return null;
}
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();
}
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);
}
}
@SuppressWarnings("TreeToString")
@Override
public Description matchMethod(final MethodTree tree, final VisitorState state) {
if ((tree.getReturnType() == null)
|| !tree.getReturnType().toString().startsWith("Optional<")
|| (tree.getBody() == null)
|| (!CONTAINS_RETURN_NULL.matches(tree.getBody(), state))) {
return Description.NO_MATCH;
}
return describeMatch(tree);
}
public BlockTree reflowMethodBody(Context context, CompilationUnitTree topLevel, ClassTree ownerClass, MethodTree methodToReparse) {
Flow flow = Flow.instance(context);
TreeMaker make = TreeMaker.instance(context);
Enter enter = Enter.instance(context);
flow.analyzeTree(enter.getEnv(((JCTree.JCClassDecl) ownerClass).sym), make);
return methodToReparse.getBody();
}
/**
* Render the source fragment for the Java language. Java being the pivot language, we consider this method as the
* _default_ behavior. This method is final as it must not be overridden by any extension.
*
* @param elt the element
* @param source the source
* @return the fragment
*/
@Override
public String renderSource(ExecutableElement elt, String source) {
// Get block
TreePath path = docTrees.getPath(elt);
MethodTree methodTree = (MethodTree) path.getLeaf();
BlockTree blockTree = methodTree.getBody();
List<? extends StatementTree> statements = blockTree.getStatements();
if (statements.size() > 0) {
return renderSource(path, statements, source);
} else {
return null;
}
}
/**
* @param entities relevant entities from class
* @param notInitializedInConstructors those fields not initialized in some constructor
* @param state visitor 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 = getTreesInstance(state);
Symbol.ClassSymbol classSymbol = entities.classSymbol();
ImmutableSet.Builder<Element> initInSomeInitializerBuilder = ImmutableSet.builder();
for (MethodTree initMethodTree : entities.instanceInitializerMethods()) {
if (initMethodTree.getBody() == null) {
continue;
}
addInitializedFieldsForBlock(
state,
trees,
classSymbol,
initInSomeInitializerBuilder,
initMethodTree.getBody(),
new TreePath(state.getPath(), initMethodTree));
}
for (BlockTree block : entities.instanceInitializerBlocks()) {
addInitializedFieldsForBlock(
state,
trees,
classSymbol,
initInSomeInitializerBuilder,
block,
new TreePath(state.getPath(), block));
}
Set<Symbol> result = new LinkedHashSet<>();
ImmutableSet<Element> initInSomeInitializer = initInSomeInitializerBuilder.build();
for (Symbol fieldSymbol : notInitializedInConstructors) {
if (!initInSomeInitializer.contains(fieldSymbol)) {
result.add(fieldSymbol);
}
}
return result;
}
public void test158154OneIf() throws Exception {
String source = "class Test {\n"
+ " void m1(boolean b) {\n"
+ " if (b) ; else System.out.println(\"hi\");\n"
+ " }\n"
+ "}";
String golden = "class Test {\n"
+ " void m1(boolean b) {\n"
+ " if (!(b)) System.out.println(\"hi\");\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 original = (IfTree) block.getStatements().get(0);
IfTree modified = make.If(
make.Parenthesized(
make.Unary(Kind.LOGICAL_COMPLEMENT, original.getCondition())),
original.getElseStatement(), null);
copy.rewrite(original, modified);
}
};
src.runModificationTask(task).commit();
String res = TestUtilities.copyFileToString(testFile);
System.out.println(res);
assertEquals(golden, res);
}
@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;
}
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");
}
public List<ErrorDescription> run(CompilationInfo compilationInfo, TreePath treePath) {
Element e = compilationInfo.getTrees().getElement(treePath);
if ( e == null
|| e.getKind() != ElementKind.METHOD
|| !"cancel".equals(e.getSimpleName().toString()) //NOI18N
|| e.getModifiers().contains(Modifier.ABSTRACT)) {
return null;
}
Element clazz = e.getEnclosingElement();
if (!clazz.getKind().isClass()) {
return null;
}
boolean found = false;
OUT: for (String toCheck : typesToCheck) {
TypeElement clazzTE = (TypeElement) clazz;
TypeMirror clazzTM = clazzTE.asType();
TypeMirror typeToCheck = compilationInfo.getTreeUtilities().parseType(toCheck, clazzTE);
if (typeToCheck.getKind() != TypeKind.DECLARED)
continue;
TypeElement typeToCheckTE = (TypeElement) ((DeclaredType) typeToCheck).asElement();
if ( compilationInfo.getTypes().isSubtype(clazzTM, typeToCheck)
&& !clazzTM.equals(typeToCheck)) {
for (ExecutableElement ee : ElementFilter.methodsIn(typeToCheckTE.getEnclosedElements())) {
if (compilationInfo.getElements().overrides((ExecutableElement) e, ee, clazzTE)) {
found = true;
break OUT;
}
}
}
}
if (!found) {
return null;
}
MethodTree mt = (MethodTree) treePath.getLeaf();
if (mt.getBody() == null || !mt.getBody().getStatements().isEmpty()) {
return null;
}
int[] span = compilationInfo.getTreeUtilities().findNameSpan((MethodTree) treePath.getLeaf());
if (span != null) {
String message = NbBundle.getMessage(EmptyCancelForCancellableTask.class, "MSG_EmptyCancel");
ErrorDescription ed = ErrorDescriptionFactory.createErrorDescription(getSeverity().toEditorSeverity(), message, compilationInfo.getFileObject(), span[0], span[1]);
return Collections.singletonList(ed);
}
return null;
}
@Hint(
displayName = "#DN_ComparatorParameterNotUsed",
description = "#DESC_ComparatorParameterNotUsed",
category = "bugs",
suppressWarnings = { "ComparatorMethodParameterNotUsed" },
enabled = true
)
@TriggerPattern("public int compare($v1, $v2) { $stmts$; } ")
public static List<ErrorDescription> run(HintContext ctx) {
CompilationInfo ci = ctx.getInfo();
Element me = ci.getTrees().getElement(ctx.getPath());
if (me == null) {
return null;
}
Element clazz = me.getEnclosingElement();
if (clazz == null || !(
clazz.getKind().isClass() ||
/* JDK8 */ (clazz.getKind().isInterface() && me.getModifiers().contains(Modifier.DEFAULT)))
) {
// method bod not valid at this point
return null;
}
TypeMirror tm = clazz.asType();
TypeElement comparableIface = ci.getElements().getTypeElement("java.lang.Comparable"); // NOI18N
// the eclosing type must implement or extend comparable
if (comparableIface == null ||
!ci.getTypes().isSubtype(tm, comparableIface.asType())) {
return null;
}
Set<VariableElement> vars = new HashSet<VariableElement>(2);
ExecutableElement ee = (ExecutableElement)me;
vars.addAll(ee.getParameters());
ComparatorParameterNotUsed v = new ComparatorParameterNotUsed(ci, vars);
MethodTree mt = (MethodTree)ctx.getPath().getLeaf();
if (mt.getBody() == null) {
return null;
}
try {
v.scan(new TreePath(ctx.getPath(), mt.getBody()), v);
} catch (StopProcessing ex) {
// nothing, just fast interrupt
}
if (v.unusedVars.isEmpty()) {
return null;
}
// the method has exactly 2 parameters:
VariableTree par1 = mt.getParameters().get(0);
VariableTree par2 = mt.getParameters().get(1);
List<? extends VariableElement> ll = new ArrayList<VariableElement>(v.unusedVars);
List<ErrorDescription> res = new ArrayList<>(ll.size());
Collections.sort(ll, Collator.getInstance());
for (VariableElement ve : ll) {
Tree vt = ve.getSimpleName() == par1.getName() ? par1 : par2;
res.add(
ErrorDescriptionFactory.forName(ctx, vt,
TEXT_ComparatorParameterNotUsed(ve.getSimpleName().toString())
));
}
return res;
}
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);
}
public void test158154TwoIfs() throws Exception {
String source = "class Test {\n"
+ " void m1(boolean b) {\n"
+ " if (b) ; else System.out.println(\"first hi\");\n"
+ " if (b) ; else System.out.println(\"second hi\");\n"
+ " System.out.println();\n"
+ " }\n"
+ "}";
String golden = "class Test {\n"
+ " void m1(boolean b) {\n"
+ " if (!(b)) System.out.println(\"first hi\");\n"
+ " if (!(b)) System.out.println(\"second hi\");\n"
+ " System.err.println();\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);
IfTree originalB = (IfTree) block.getStatements().get(1);
IfTree modifiedA = make.If(
make.Parenthesized(
make.Unary(Kind.LOGICAL_COMPLEMENT, originalA.getCondition())),
originalA.getElseStatement(), null);
copy.rewrite(originalA, modifiedA);
IfTree modifiedB = make.If(
make.Parenthesized(
make.Unary(Kind.LOGICAL_COMPLEMENT, originalB.getCondition())),
originalB.getElseStatement(), null);
copy.rewrite(originalB, modifiedB);
Tree originalC = block.getStatements().get(2);
Tree modifiedC = make.ExpressionStatement(make.MethodInvocation(
Collections.<ExpressionTree>emptyList(),
make.MemberSelect(
make.MemberSelect(make.QualIdent("java.lang.System"), "err"),
"println"), Collections.<ExpressionTree>emptyList()));
copy.rewrite(originalC, modifiedC);
}
};
src.runModificationTask(task).commit();
String res = TestUtilities.copyFileToString(testFile);
System.out.println(res);
assertEquals(golden, res);
}
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);
}
public void testMoveStatements() throws Exception {
testFile = new File(getWorkDir(), "Test.java");
TestUtilities.copyStringToFile(testFile,
"package hierbas.del.litoral;\n\n" +
"public class Test {\n" +
" public void taragui() {\n" +
" System.err.println(1);\n" +
" System.err.println(2);\n" +
"\n" +
"\n" +
" System.err.println(3);System.err.println(3.5);\n" +
" System. err.\n" +
" println(4);\n" +
" System.err.println(5);\n" +
" }\n" +
"}\n"
);
String golden =
"package hierbas.del.litoral;\n\n" +
"public class Test {\n" +
" public void taragui() {\n" +
" System.err.println(1);\n" +
" {\n" +
" System.err.println(2);\n" +
" \n" +
" \n" +
" System.err.println(3);System.err.println(3.5);\n" +
" System. err.\n" +
" println(4);\n" +
" }\n" +
" System.err.println(5);\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();
CompilationUnitTree cut = workingCopy.getCompilationUnit();
ClassTree clazz = (ClassTree) cut.getTypeDecls().get(0);
MethodTree method = (MethodTree) clazz.getMembers().get(1);
BlockTree body = method.getBody();
BlockTree inner = make.Block(body.getStatements().subList(1, 5), false);
BlockTree nue = make.Block(Arrays.asList(body.getStatements().get(0), inner, body.getStatements().get(5)), false);
workingCopy.rewrite(body, nue);
}
};
src.runModificationTask(task).commit();
String res = TestUtilities.copyFileToString(testFile);
//System.err.println(res);
assertEquals(golden, res);
}
public void testMoveStatements2() throws Exception {
testFile = new File(getWorkDir(), "Test.java");
TestUtilities.copyStringToFile(testFile,
"package hierbas.del.litoral;\n\n" +
"public class Test {\n" +
" public void taragui() {\n" +
" System.err.println(1);\n" +
" {\n" +
" while (true) {\n" +
" System.err.println(2);\n" +
"\n" +
"\n" +
" System.err.println(3);System.err.println(3.5);\n" +
" System. err.\n" +
" println(4);\n" +
" }\n" +
" }\n" +
" if (true) {\n" +
" System.err.println(5);\n" +
" }\n" +
" }\n" +
"}\n"
);
String golden =
"package hierbas.del.litoral;\n\n" +
"public class Test {\n" +
" public void taragui() {\n" +
" System.err.println(1);\n" +
" if (true) {\n" +
" System.err.println(2);\n" +
" \n" +
" \n" +
" System.err.println(3);System.err.println(3.5);\n" +
" System. err.\n" +
" println(4);\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();
CompilationUnitTree cut = workingCopy.getCompilationUnit();
ClassTree clazz = (ClassTree) cut.getTypeDecls().get(0);
MethodTree method = (MethodTree) clazz.getMembers().get(1);
BlockTree body = method.getBody();
BlockTree block = (BlockTree)body.getStatements().get(1);
WhileLoopTree loop = (WhileLoopTree)block.getStatements().get(0);
IfTree inner = make.If(make.Parenthesized(make.Literal(Boolean.TRUE)), loop.getStatement(), null);
BlockTree nue = make.Block(Arrays.asList(body.getStatements().get(0), inner), false);
workingCopy.rewrite(body, nue);
}
};
src.runModificationTask(task).commit();
String res = TestUtilities.copyFileToString(testFile);
//System.err.println(res);
assertEquals(golden, res);
}
public void test192753() throws Exception {
setCodePreferences(NO_TAB_EXPAND_PREFERENCES);
testFile = new File(getWorkDir(), "Test.java");
TestUtilities.copyStringToFile(testFile,
"package hierbas.del.litoral;\n\n" +
"public class Test {\n" +
" public void taragui(String str) {\n" +
"\tint a = 0;\n" +
"\tSystem.err.println(1);\n" +
"\tSystem.err.println(2);\n" +
" }\n" +
"}\n"
);
String golden =
"package hierbas.del.litoral;\n\n" +
"public class Test {\n" +
" public void taragui(String str) {\n" +
"\tint a = 0;\n" +
" }\n\n" +
" void nue() {\n" +
"\tSystem.err.println(1);\n" +
"\tSystem.err.println(2);\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();
CompilationUnitTree cut = workingCopy.getCompilationUnit();
ClassTree clazz = (ClassTree) cut.getTypeDecls().get(0);
MethodTree method = (MethodTree) clazz.getMembers().get(1);
BlockTree body = method.getBody();
BlockTree nueBlock = make.Block(body.getStatements().subList(1, body.getStatements().size()), false);
MethodTree nueMethod = make.Method(make.Modifiers(EnumSet.noneOf(Modifier.class)), "nue", make.PrimitiveType(TypeKind.VOID), Collections.<TypeParameterTree>emptyList(), Collections.<VariableTree>emptyList(), Collections.<ExpressionTree>emptyList(), nueBlock, null);
workingCopy.rewrite(clazz, make.addClassMember(clazz, nueMethod));
workingCopy.rewrite(body, make.Block(body.getStatements().subList(0, 1), false));
}
};
src.runModificationTask(task).commit();
String res = TestUtilities.copyFileToString(testFile);
//System.err.println(res);
assertEquals(golden, res);
}
public void testModifySetter() throws Exception {
testFile = new File(getWorkDir(), "Test.java");
TestUtilities.copyStringToFile(testFile,
"package personal;\n" +
"\n" +
"public class Test {\n" +
" public Object method(Class o) {\n" +
" }\n" +
" \n" +
" public String getText() {\n" +
" }\n" +
" \n" +
" public void setText() {\n" +
" System.out.println(\"Text\");\n" +
" }\n" +
" \n" +
" public Object method2(Class o) {\n" +
" }\n" +
" \n" +
"}\n");
String golden =
"package personal;\n" +
"\n" +
"public class Test {\n" +
"\n" +
" private int i;\n" +
" public Object method(Class o) {\n" +
" }\n" +
" \n" +
" public String getText() {\n" +
" }\n" +
" \n" +
" public void setText() {\n" +
" System.out.println(\"Test\");\n" +
" System.out.println(\"Text\");\n" +
" System.out.println(\"Test\");\n" +
" }\n" +
" \n" +
" public Object method2(Class o) {\n" +
" }\n" +
" \n" +
"}\n";
JavaSource testSource = JavaSource.forFileObject(FileUtil.toFileObject(testFile));
Task task = new Task<WorkingCopy>() {
public void run(WorkingCopy workingCopy) throws IOException {
workingCopy.toPhase(org.netbeans.api.java.source.JavaSource.Phase.RESOLVED);
TreeMaker make = workingCopy.getTreeMaker();
ClassTree clazz = (ClassTree)workingCopy.getCompilationUnit().getTypeDecls().get(0);
MethodTree method = (MethodTree)clazz.getMembers().get(3);
BlockTree block = method.getBody();
VariableTree var = make.Variable(make.Modifiers(EnumSet.of(Modifier.PRIVATE)), "i", make.Type(workingCopy.getTypes().getPrimitiveType(TypeKind.INT)), null);
ClassTree clazzCopy = make.insertClassMember(clazz, 0, var);
workingCopy.rewrite(clazz, clazzCopy);
ExpressionStatementTree est = make.ExpressionStatement(
make.MethodInvocation(
Collections.<ExpressionTree>emptyList(),
make.MemberSelect(
make.MemberSelect(
make.Identifier("System"),
"out"
),
"println"
),
Collections.<ExpressionTree>singletonList(
make.Literal("Test")
)
)
);
BlockTree bt = make.addBlockStatement(block, est);
bt = make.insertBlockStatement(bt, 0, est);
workingCopy.rewrite(block, bt);
}
};
testSource.runModificationTask(task).commit();
String res = TestUtilities.copyFileToString(testFile);
//System.err.println(res);
assertEquals(golden, res);
}