下面列出了com.sun.source.tree.MethodTree#getModifiers ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Override
public Description matchMethod(final MethodTree tree, final VisitorState state) {
final ModifiersTree mods = tree.getModifiers();
if (isAbstraction) {
if (isConcreteMethod(mods)) {
return matchParameters(tree);
}
} else if (isNotAbstract(mods)) {
return matchParameters(tree);
}
return Description.NO_MATCH;
}
/**
* Original:
*
* void method() {
* }
*
* Result:
*
* public static void method() {
* }
*/
public void testMethodMods1() 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" +
" void method() {\n" +
" }\n" +
"}\n"
);
String golden =
"package hierbas.del.litoral;\n\n" +
"import java.io.*;\n\n" +
"public class Test {\n" +
" public static void method() {\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);
ModifiersTree mods = method.getModifiers();
workingCopy.rewrite(mods, make.Modifiers(EnumSet.of(Modifier.PUBLIC, Modifier.STATIC)));
}
};
testSource.runModificationTask(task).commit();
String res = TestUtilities.copyFileToString(testFile);
//System.err.println(res);
assertEquals(golden, res);
}
/**
* Original:
*
* public static void method() {
* }
*
* Result:
*
* void method() {
* }
*/
public void testMethodMods2() 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 static void method() {\n" +
" }\n" +
"}\n"
);
String golden =
"package hierbas.del.litoral;\n\n" +
"import java.io.*;\n\n" +
"public class Test {\n" +
" void method() {\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);
ModifiersTree mods = method.getModifiers();
workingCopy.rewrite(mods, make.Modifiers(Collections.<Modifier>emptySet()));
}
};
testSource.runModificationTask(task).commit();
String res = TestUtilities.copyFileToString(testFile);
//System.err.println(res);
assertEquals(golden, res);
}
/**
* Original:
*
* Test() {
* }
*
* Result:
*
* public Test() {
* }
*/
public void testMethodMods3() 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" +
" Test() {\n" +
" }\n" +
"}\n"
);
String golden =
"package hierbas.del.litoral;\n\n" +
"import java.io.*;\n\n" +
"public class Test {\n" +
" public Test() {\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(0);
ModifiersTree mods = method.getModifiers();
workingCopy.rewrite(mods, make.Modifiers(Collections.<Modifier>singleton(Modifier.PUBLIC)));
}
};
testSource.runModificationTask(task).commit();
String res = TestUtilities.copyFileToString(testFile);
//System.err.println(res);
assertEquals(golden, res);
}
/**
* Original:
*
* public Test() {
* }
*
* Result:
*
* Test() {
* }
*/
public void testMethodMods4() 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 Test() {\n" +
" }\n" +
"}\n"
);
String golden =
"package hierbas.del.litoral;\n\n" +
"import java.io.*;\n\n" +
"public class Test {\n" +
" Test() {\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(0);
ModifiersTree mods = method.getModifiers();
workingCopy.rewrite(mods, make.Modifiers(Collections.<Modifier>emptySet()));
}
};
testSource.runModificationTask(task).commit();
String res = TestUtilities.copyFileToString(testFile);
//System.err.println(res);
assertEquals(golden, res);
}
/**
* Original:
*
* public static void method() {
* }
*
* Result:
*
* static void method() {
* }
*/
public void testMethodMods5() 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 static void method() {\n" +
" }\n" +
"}\n"
);
String golden =
"package hierbas.del.litoral;\n\n" +
"import java.io.*;\n\n" +
"public class Test {\n" +
" static void method() {\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);
ModifiersTree mods = method.getModifiers();
workingCopy.rewrite(mods, make.Modifiers(Collections.<Modifier>singleton(Modifier.STATIC)));
}
};
testSource.runModificationTask(task).commit();
String res = TestUtilities.copyFileToString(testFile);
//System.err.println(res);
assertEquals(golden, res);
}
/**
* Original:
*
* public Test() {
* }
*
* Result:
*
* protected Test() {
* }
*/
public void testMethodMods6() 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 Test() {\n" +
" }\n" +
"}\n"
);
String golden =
"package hierbas.del.litoral;\n\n" +
"import java.io.*;\n\n" +
"public class Test {\n" +
" protected Test() {\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(0);
ModifiersTree mods = method.getModifiers();
workingCopy.rewrite(mods, make.Modifiers(Collections.<Modifier>singleton(Modifier.PROTECTED)));
}
};
testSource.runModificationTask(task).commit();
String res = TestUtilities.copyFileToString(testFile);
//System.err.println(res);
assertEquals(golden, res);
}
public void test124701() throws Exception {
testFile = new File(getWorkDir(), "Test.java");
TestUtilities.copyStringToFile(testFile,
"package flaska;\n" +
"\n" +
"public class Test {\n" +
" @SuppressWarnings(\"x\")\n" +
" private void alois() {\n" +
" }\n" +
" \n" +
"}\n"
);
String golden =
"package flaska;\n" +
"\n" +
"public class Test {\n" +
" @SuppressWarnings(\"x\")\n" +
" public void alois() {\n" +
" }\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();
ClassTree clazz = (ClassTree) workingCopy.getCompilationUnit().getTypeDecls().get(0);
MethodTree method = (MethodTree) clazz.getMembers().get(1);
ModifiersTree mods = method.getModifiers();
ModifiersTree copy = make.Modifiers(EnumSet.of(Modifier.PUBLIC), mods.getAnnotations());
workingCopy.rewrite(mods, copy);
}
};
testSource.runModificationTask(task).commit();
String res = TestUtilities.copyFileToString(testFile);
//System.err.println(res);
assertEquals(golden, res);
}
private static boolean isInHeader(CompilationInfo info, MethodTree tree, int offset) {
CompilationUnitTree cut = info.getCompilationUnit();
SourcePositions sp = info.getTrees().getSourcePositions();
long lastKnownOffsetInHeader = sp.getStartPosition(cut, tree);
List<? extends ExpressionTree> throwz;
List<? extends VariableTree> params;
List<? extends TypeParameterTree> typeparams;
if ((throwz = tree.getThrows()) != null && !throwz.isEmpty()) {
lastKnownOffsetInHeader = sp.getEndPosition(cut, throwz.get(throwz.size() - 1));
} else if ((params = tree.getParameters()) != null && !params.isEmpty()) {
lastKnownOffsetInHeader = sp.getEndPosition(cut, params.get(params.size() - 1));
} else if ((typeparams = tree.getTypeParameters()) != null && !typeparams.isEmpty()) {
lastKnownOffsetInHeader = sp.getEndPosition(cut, typeparams.get(typeparams.size() - 1));
} else if (tree.getReturnType() != null) {
lastKnownOffsetInHeader = sp.getEndPosition(cut, tree.getReturnType());
} else if (tree.getModifiers() != null) {
lastKnownOffsetInHeader = sp.getEndPosition(cut, tree.getModifiers());
}
TokenSequence<JavaTokenId> ts = info.getTreeUtilities().tokensFor(tree);
ts.move((int) lastKnownOffsetInHeader);
while (ts.moveNext()) {
if (ts.token().id() == JavaTokenId.LBRACE || ts.token().id() == JavaTokenId.SEMICOLON) {
return offset < ts.offset();
}
}
return false;
}
private TreeNode convertAnnotationTypeDeclaration(ClassTree node, TreePath parent) {
AnnotationTypeDeclaration newNode = new AnnotationTypeDeclaration();
TreePath path = getTreePath(parent, node);
Element element = getElement(path);
convertBodyDeclaration(node, path, node.getModifiers(), newNode);
for (Tree bodyDecl : node.getMembers()) {
if (bodyDecl.getKind() == Kind.METHOD) {
MethodTree methodTree = (MethodTree) bodyDecl;
TreePath methodPath = getTreePath(path, methodTree);
ExecutableElement methodElement = (ExecutableElement) getElement(methodPath);
Tree defaultValue = methodTree.getDefaultValue();
ModifiersTree modifiers = methodTree.getModifiers();
AnnotationTypeMemberDeclaration newMember =
new AnnotationTypeMemberDeclaration()
.setDefault((Expression) convert(defaultValue, methodPath))
.setExecutableElement(methodElement);
newMember
.setModifiers((int) ((JCModifiers) modifiers).flags)
.setAnnotations(convertAnnotations(modifiers, getTreePath(methodPath, modifiers)))
.setJavadoc((Javadoc) getAssociatedJavaDoc(methodTree, methodPath));
newNode.addBodyDeclaration(newMember);
} else {
newNode.addBodyDeclaration((BodyDeclaration) convert(bodyDecl, path));
}
}
return newNode
.setName(convertSimpleName(element, getTypeMirror(path), getNamePosition(node)))
.setTypeElement((TypeElement) element);
}
public ClassTree ensureNoArgConstructor(ClassTree classTree) {
TypeElement typeElement = SourceUtils.classTree2TypeElement(copy, classTree);
if (typeElement == null) {
throw new IllegalArgumentException("No TypeElement for ClassTree " + classTree.getSimpleName());
}
ExecutableElement constructor = SourceUtils.getNoArgConstructor(copy, typeElement);
MethodTree constructorTree = constructor != null ? copy.getTrees().getTree(constructor) : null;
MethodTree newConstructorTree = null;
TreeMaker make = getTreeMaker();
if (constructor != null) {
if (!constructor.getModifiers().contains(Modifier.PUBLIC)) {
ModifiersTree oldModifiersTree = constructorTree.getModifiers();
Set newModifiers = EnumSet.of(Modifier.PUBLIC);
// for (Modifier modifier : oldModifiersTree.getFlags()) {
// if (!Modifier.PROTECTED.equals(modifier) && !Modifier.PRIVATE.equals(modifier)) {
// newModifiers.add(modifier);
// }
//}
newConstructorTree = make.Constructor(
make.Modifiers(newModifiers),
constructorTree.getTypeParameters(),
constructorTree.getParameters(),
constructorTree.getThrows(),
constructorTree.getBody());
}
} else {
newConstructorTree = make.Constructor(
createModifiers(Modifier.PUBLIC),
Collections.<TypeParameterTree>emptyList(),
Collections.<VariableTree>emptyList(),
Collections.<ExpressionTree>emptyList(),
"{ }"); // NOI18N
}
ClassTree newClassTree = classTree;
if (newConstructorTree != null) {
if (constructorTree != null) {
newClassTree = make.removeClassMember(newClassTree, constructorTree);
}
newClassTree = make.addClassMember(newClassTree, newConstructorTree);
}
return newClassTree;
}
/**
* Ensures the given class has a public no-arg constructor.
*
* @param classTree the class to ensure the constructor for; cannot be null.
* @return a modified class if a no-arg constructor was added, the original
* class otherwise; never null.
*/
public ClassTree ensureNoArgConstructor(ClassTree classTree) {
TypeElement typeElement = SourceUtils.classTree2TypeElement(copy, classTree);
if (typeElement == null) {
throw new IllegalArgumentException("No TypeElement for ClassTree " + classTree.getSimpleName());
}
ExecutableElement constructor = SourceUtils.getNoArgConstructor(copy, typeElement);
MethodTree constructorTree = constructor != null ? copy.getTrees().getTree(constructor) : null;
MethodTree newConstructorTree = null;
TreeMaker make = getTreeMaker();
if (constructor != null) {
if (!constructor.getModifiers().contains(Modifier.PUBLIC)) {
ModifiersTree oldModifiersTree = constructorTree.getModifiers();
Set<Modifier> newModifiers = EnumSet.of(Modifier.PUBLIC);
for (Modifier modifier : oldModifiersTree.getFlags()) {
if (!Modifier.PROTECTED.equals(modifier) && !Modifier.PRIVATE.equals(modifier)) {
newModifiers.add(modifier);
}
}
newConstructorTree = make.Constructor(
make.Modifiers(newModifiers),
constructorTree.getTypeParameters(),
constructorTree.getParameters(),
constructorTree.getThrows(),
constructorTree.getBody());
}
} else {
newConstructorTree = make.Constructor(
createModifiers(Modifier.PUBLIC),
Collections.<TypeParameterTree>emptyList(),
Collections.<VariableTree>emptyList(),
Collections.<ExpressionTree>emptyList(),
"{ }"); // NOI18N
}
ClassTree newClassTree = classTree;
if (newConstructorTree != null) {
if (constructorTree != null) {
newClassTree = make.removeClassMember(newClassTree, constructorTree);
}
newClassTree = make.addClassMember(newClassTree, newConstructorTree);
}
return newClassTree;
}
protected ModifiersTree getTargetModifiers(VariableTree fieldTree, MethodTree methodTree) {
return methodTree.getModifiers();
}
protected ModifiersTree getSourceModifiers(VariableTree fieldTree, MethodTree methodTree) {
return methodTree.getModifiers();
}
private ClassTree createAsyncMethod( TreeMaker maker,
String asyncName, String service, MethodTree method, String movedName ,
WorkingCopy copy, ClassTree classTree, boolean isEjb)
{
ModifiersTree modifiers = method.getModifiers();
if ( isEjb ){
AnnotationTree async = maker.Annotation(maker.QualIdent(
"javax.ejb.Asynchronous"), // NOI18N
Collections.<ExpressionTree>emptyList());
modifiers = maker.addModifiersAnnotation(modifiers, async);
}
List<? extends VariableTree> parameters = method.getParameters();
String asyncReponseParam = getAsynParam("asyncResponse",parameters);//NOI18N
ModifiersTree paramModifier = maker.Modifiers(EnumSet.of(Modifier.FINAL));
AnnotationTree annotation = maker.Annotation(
maker.QualIdent("javax.ws.rs.container.Suspended"), // NOI18N
Collections.<ExpressionTree>emptyList());
paramModifier = maker.Modifiers(paramModifier,
Collections.singletonList(annotation));
VariableTree asyncParam = maker.Variable(paramModifier, asyncReponseParam,
maker.QualIdent("javax.ws.rs.container.AsyncResponse"), null);//NOI18N
List<VariableTree> params = new ArrayList<VariableTree>(parameters.size()+1);
params.add(asyncParam);
Tree returnType = method.getReturnType();
boolean noReturn =returnType.toString().equals("void"); // NOI18N
StringBuilder body = new StringBuilder("{"); // NOI18N
if ( !isEjb ){
body.append(service);
body.append(".submit(new Runnable() { public void run() {");//NOI18N
}
if ( !noReturn ){
body.append(asyncReponseParam);
body.append(".resume("); // NOI18N
}
body.append(movedName);
body.append('(');
for (VariableTree param : parameters) {
ModifiersTree modifier = maker.addModifiersModifier(param.getModifiers(),
Modifier.FINAL);
VariableTree newParam = maker.Variable(modifier, param.getName(),
param.getType(), param.getInitializer());
params.add(newParam);
TreePath pathParam = copy.getTrees().getPath(
copy.getCompilationUnit(), param);
body.append(copy.getTrees().getElement(pathParam).getSimpleName());
body.append(',');
}
if ( !parameters.isEmpty()){
body.deleteCharAt(body.length()-1);
}
if ( noReturn){
body.append(");");
body.append(asyncReponseParam);
body.append(".resume(javax.ws.rs.core.Response.ok().build());");//NOI18N
}
else {
body.append("));");
}
if ( !isEjb ){
body.append("}});");
}
body.append('}');
MethodTree newMethod = maker.Method(modifiers, asyncName,
maker.Type("void"), // NOI18N
Collections.<TypeParameterTree> emptyList(),
params,
Collections.<ExpressionTree> emptyList(),
body.toString(),null);
return maker.addClassMember(classTree, newMethod);
}
/**
* Ensures the given class has a public no-arg constructor.
*
* @param classTree the class to ensure the constructor for; cannot be null.
* @return a modified class if a no-arg constructor was added, the original
* class otherwise; never null.
*/
public ClassTree ensureNoArgConstructor(ClassTree classTree) {
TypeElement typeElement = SourceUtils.classTree2TypeElement(copy, classTree);
if (typeElement == null) {
throw new IllegalArgumentException("No TypeElement for ClassTree " + classTree.getSimpleName());
}
ExecutableElement constructor = SourceUtils.getNoArgConstructor(copy, typeElement);
MethodTree constructorTree = constructor != null ? copy.getTrees().getTree(constructor) : null;
MethodTree newConstructorTree = null;
TreeMaker make = getTreeMaker();
if (constructor != null) {
if (!constructor.getModifiers().contains(Modifier.PUBLIC)) {
ModifiersTree oldModifiersTree = constructorTree.getModifiers();
Set<Modifier> newModifiers = EnumSet.of(Modifier.PUBLIC);
for (Modifier modifier : oldModifiersTree.getFlags()) {
if (!Modifier.PROTECTED.equals(modifier) && !Modifier.PRIVATE.equals(modifier)) {
newModifiers.add(modifier);
}
}
newConstructorTree = make.Constructor(
make.Modifiers(newModifiers),
constructorTree.getTypeParameters(),
constructorTree.getParameters(),
constructorTree.getThrows(),
constructorTree.getBody());
}
} else {
newConstructorTree = make.Constructor(
createModifiers(Modifier.PUBLIC),
Collections.<TypeParameterTree>emptyList(),
Collections.<VariableTree>emptyList(),
Collections.<ExpressionTree>emptyList(),
"{ }"); // NOI18N
}
ClassTree newClassTree = classTree;
if (newConstructorTree != null) {
if (constructorTree != null) {
newClassTree = make.removeClassMember(newClassTree, constructorTree);
}
newClassTree = make.addClassMember(newClassTree, newConstructorTree);
}
return newClassTree;
}