本文整理匯總了Java中com.sun.source.tree.MethodTree類的典型用法代碼示例。如果您正苦於以下問題:Java MethodTree類的具體用法?Java MethodTree怎麽用?Java MethodTree使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。
MethodTree類屬於com.sun.source.tree包,在下文中一共展示了MethodTree類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。
示例1: tooDeepNesting
import com.sun.source.tree.MethodTree; //導入依賴的package包/類
@Hint(
category = "metrics",
displayName = "#DN_MethodTooDeepNesting",
description = "#DESC_MethodTooDeepNesting",
options = { Hint.Options.QUERY, Hint.Options.HEAVY },
enabled = false
)
@TriggerTreeKind(Tree.Kind.METHOD)
@UseOptions(value = { OPTION_NESTING_LIMIT })
public static ErrorDescription tooDeepNesting(HintContext ctx) {
Tree t = ctx.getPath().getLeaf();
MethodTree method = (MethodTree)t;
DepthVisitor v = new DepthVisitor();
v.scan(ctx.getPath(), null);
int depth = v.getDepth();
int treshold = ctx.getPreferences().getInt(OPTION_NESTING_LIMIT, DEFAULT_NESTING_LIMIT);
if (depth <= treshold) {
return null;
}
return ErrorDescriptionFactory.forName(ctx, t,
methodOrConstructor(ctx) ?
TEXT_ConstructorTooDeepNesting(depth) :
TEXT_MethodTooDeepNesting(method.getName().toString(), depth)
);
}
示例2: makeUnique
import com.sun.source.tree.MethodTree; //導入依賴的package包/類
private String makeUnique(String methodName){
List <? extends Tree> members=getClassTree().getMembers();
String name=methodName;
int add=1;
boolean found=false;
do
{
found=false;
for(Tree membr:members) {
if(Tree.Kind.METHOD.equals(membr.getKind())){
MethodTree mt = membr instanceof MethodTree ? (MethodTree) membr : null;
if(mt!=null && name.equals(mt.getName().toString())) {
found = true;
name = methodName + add++;
}
}
}
}while(found);
return name;
}
示例3: testStartPositionForMethodWithoutModifiers
import com.sun.source.tree.MethodTree; //導入依賴的package包/類
@Test
void testStartPositionForMethodWithoutModifiers() throws IOException {
String code = "package t; class Test { <T> void t() {} }";
JavacTaskImpl ct = (JavacTaskImpl) tool.getTask(null, fm, null, null,
null, Arrays.asList(new MyFileObject(code)));
CompilationUnitTree cut = ct.parse().iterator().next();
ClassTree clazz = (ClassTree) cut.getTypeDecls().get(0);
MethodTree mt = (MethodTree) clazz.getMembers().get(0);
Trees t = Trees.instance(ct);
int start = (int) t.getSourcePositions().getStartPosition(cut, mt);
int end = (int) t.getSourcePositions().getEndPosition(cut, mt);
assertEquals("testStartPositionForMethodWithoutModifiers",
"<T> void t() {}", code.substring(start, end));
}
示例4: multipleLoops
import com.sun.source.tree.MethodTree; //導入依賴的package包/類
@Hint(
category = "metrics",
displayName = "#DN_MethodMultipleLoops",
description = "#DESC_MethodMultipleLoops",
options = { Hint.Options.QUERY, Hint.Options.HEAVY },
enabled = false
)
@TriggerTreeKind(Tree.Kind.METHOD)
@UseOptions({ OPTION_LOOPS_LIMIT })
public static ErrorDescription multipleLoops(HintContext ctx) {
Tree t = ctx.getPath().getLeaf();
MethodTree method = (MethodTree)t;
LoopFinder v = new LoopFinder();
v.scan(ctx.getPath(), null);
int count = v.getLoopCount();
int limit = ctx.getPreferences().getInt(OPTION_LOOPS_LIMIT, DEFAULT_LOOPS_LIMIT);
if (count > limit) {
return ErrorDescriptionFactory.forName(ctx, t,
TEXT_MethodMultipleLoops(method.getName().toString(), count)
);
} else {
return null;
}
}
示例5: createMethod
import com.sun.source.tree.MethodTree; //導入依賴的package包/類
private static MethodTree createMethod(WorkingCopy wc, MethodInfo mInfo) {
TreeMaker make = wc.getTreeMaker();
TypeInfo[] pTypes = mInfo.getParameterTypes();
String[] pNames = mInfo.getParameterNames();
List<VariableTree> params = new ArrayList<VariableTree>();
for (int i = 0 ; pTypes != null && i < pTypes.length; i++) {
VariableTree vtree = createVariable(wc, pNames[i], pTypes[i]);
params.add(vtree);
}
TypeInfo[] excepTypes = mInfo.getExceptionTypes();
List<ExpressionTree> throwsList = new ArrayList<ExpressionTree>();
for (int i = 0 ; excepTypes != null && i < excepTypes.length; i++) {
throwsList.add((ExpressionTree)createType(wc, excepTypes[i]));
}
String body = mInfo.getMethodBodyText();
if(body == null) {
body = "";
}
MethodTree mtree = make.Method(createModifiers(wc, mInfo.getModifiers(), mInfo.getAnnotations()),
mInfo.getName(),
createType(wc, mInfo.getReturnType()),
Collections.<TypeParameterTree>emptyList(),
params,
throwsList,
"{" + body + "}",
null
);
// if(mInfo.getCommentText() != null) {
// Comment comment = Comment.create(Comment.Style.JAVADOC, -2,
// -2, -2, mInfo.getCommentText());
// make.addComment(mtree, comment, true);
// }
return mtree;
}
示例6: createEqualsMethod
import com.sun.source.tree.MethodTree; //導入依賴的package包/類
public MethodTree createEqualsMethod(String simpleClassName, List<VariableTree> fields) {
StringBuilder body = new StringBuilder(50 + fields.size() * 30);
body.append("{"); // NOI18N
body.append("// TODO: Warning - this method won't work in the case the id fields are not set\n"); // NOI18N
body.append("if (!(object instanceof "); // NOI18N
body.append(simpleClassName + ")) {return false;}"); // NOI18N
body.append(simpleClassName + " other = (" + simpleClassName + ")object;"); // NOI18N
for (VariableTree field : fields) {
body.append(createEqualsLineForField(field));
}
body.append("return true;"); // NOI18N
body.append("}"); // NOI18N
TreeMaker make = copy.getTreeMaker();
// XXX Javadoc
return make.Method(make.Modifiers(EnumSet.of(Modifier.PUBLIC),
Collections.singletonList(genUtils.createAnnotation("java.lang.Override"))), "equals",
make.PrimitiveType(TypeKind.BOOLEAN), Collections.<TypeParameterTree>emptyList(),
Collections.singletonList(genUtils.createVariable(scope, "object", "java.lang.Object")),
Collections.<ExpressionTree>emptyList(), body.toString(), null);
}
示例7: createToStringMethod
import com.sun.source.tree.MethodTree; //導入依賴的package包/類
public MethodTree createToStringMethod(String fqn, List<VariableTree> fields) {
StringBuilder body = new StringBuilder(30 + fields.size() * 30);
body.append("{"); // NOI18N
body.append("return \"" + fqn + "[ "); // NOI18N
for (Iterator<VariableTree> i = fields.iterator(); i.hasNext();) {
String fieldName = i.next().getName().toString();
body.append(fieldName + "=\" + " + fieldName + " + \""); //NOI18N
body.append(i.hasNext() ? ", " : " ]\";"); //NOI18N
}
body.append("}"); // NOI18N
TreeMaker make = copy.getTreeMaker();
// XXX Javadoc
return make.Method(make.Modifiers(EnumSet.of(Modifier.PUBLIC),
Collections.singletonList(genUtils.createAnnotation("java.lang.Override"))), "toString",
genUtils.createType("java.lang.String", scope), Collections.<TypeParameterTree>emptyList(),
Collections.<VariableTree>emptyList(), Collections.<ExpressionTree>emptyList(), body.toString(), null);
}
示例8: onMatchReturn
import com.sun.source.tree.MethodTree; //導入依賴的package包/類
@Override
public void onMatchReturn(NullAway analysis, ReturnTree tree, VisitorState state) {
// Figure out the enclosing method node
TreePath enclosingMethodOrLambda =
NullabilityUtil.findEnclosingMethodOrLambdaOrInitializer(state.getPath());
if (enclosingMethodOrLambda == null) {
throw new RuntimeException("no enclosing method, lambda or initializer!");
}
if (!(enclosingMethodOrLambda.getLeaf() instanceof MethodTree
|| enclosingMethodOrLambda.getLeaf() instanceof LambdaExpressionTree)) {
throw new RuntimeException(
"return statement outside of a method or lambda! (e.g. in an initializer block)");
}
Tree leaf = enclosingMethodOrLambda.getLeaf();
if (filterMethodOrLambdaSet.contains(leaf)) {
returnToEnclosingMethodOrLambda.put(tree, leaf);
// We need to manually trigger the dataflow analysis to run on the filter method,
// this ensures onDataflowVisitReturn(...) gets called for all return statements in this
// method before
// onDataflowInitialStore(...) is called for all successor methods in the observable chain.
// Caching should prevent us from re-analyzing any given method.
AccessPathNullnessAnalysis nullnessAnalysis = analysis.getNullnessAnalysis(state);
nullnessAnalysis.forceRunOnMethod(new TreePath(state.getPath(), leaf), state.context);
}
}
示例9: indexController
import com.sun.source.tree.MethodTree; //導入依賴的package包/類
private void indexController() {
for (Tree member : controllerClass.getMembers()) {
switch (member.getKind()) {
case VARIABLE: {
VariableTree vt = (VariableTree)member;
fields.put(vt.getName().toString(), vt);
break;
}
case METHOD: {
MethodTree mt = (MethodTree)member;
addMethod(mt);
break;
}
}
}
}
示例10: composeNewTestMethod
import com.sun.source.tree.MethodTree; //導入依賴的package包/類
/**
*/
protected MethodTree composeNewTestMethod(String testMethodName,
BlockTree testMethodBody,
List<ExpressionTree> throwsList,
WorkingCopy workingCopy) {
TreeMaker maker = workingCopy.getTreeMaker();
return maker.Method(
maker.Modifiers(createModifierSet(PUBLIC)),
testMethodName,
maker.PrimitiveType(TypeKind.VOID),
Collections.<TypeParameterTree>emptyList(),
Collections.<VariableTree>emptyList(),
throwsList,
testMethodBody,
null); //default value - used by annotations
}
示例11: createMainMethod
import com.sun.source.tree.MethodTree; //導入依賴的package包/類
/**
* Creates a public static {@code main(String[])} method
* with the body taken from settings.
*
* @param maker {@code TreeMaker} to use for creating the method
* @return created {@code main(...)} method,
* or {@code null} if the method body would be empty
*/
private MethodTree createMainMethod(TreeMaker maker) {
String initialMainMethodBody = getInitialMainMethodBody();
if (initialMainMethodBody.length() == 0) {
return null;
}
ModifiersTree modifiers = maker.Modifiers(
createModifierSet(Modifier.PUBLIC, Modifier.STATIC));
VariableTree param = maker.Variable(
maker.Modifiers(Collections.<Modifier>emptySet()),
"argList", //NOI18N
maker.Identifier("String[]"), //NOI18N
null); //initializer - not used in params
MethodTree mainMethod = maker.Method(
modifiers, //public static
"main", //method name "main"//NOI18N
maker.PrimitiveType(TypeKind.VOID), //return type "void"
Collections.<TypeParameterTree>emptyList(), //type params
Collections.<VariableTree>singletonList(param), //method param
Collections.<ExpressionTree>emptyList(), //throws-list
'{' + initialMainMethodBody + '}', //body text
null); //only for annotations
return mainMethod;
}
示例12: addInitMethod
import com.sun.source.tree.MethodTree; //導入依賴的package包/類
/**
*/
private void addInitMethod(String methodName,
String annotationClassName,
boolean isStatic,
int targetIndex,
List<Tree> clsMembers,
ClassMap clsMap,
WorkingCopy workingCopy) {
MethodTree initMethod = generateInitMethod(methodName,
annotationClassName,
isStatic,
workingCopy);
if (targetIndex == -1) {
targetIndex = getPlaceForFirstInitMethod(clsMap);
}
if (targetIndex != -1) {
clsMembers.add(targetIndex, initMethod);
} else {
clsMembers.add(initMethod);
}
clsMap.addNoArgMethod(methodName, annotationClassName, targetIndex);
}
示例13: performRewrite
import com.sun.source.tree.MethodTree; //導入依賴的package包/類
@Override
protected void performRewrite(TransformationContext ctx) {
WorkingCopy wc = ctx.getWorkingCopy();
TreePath tp = ctx.getPath();
TypeMirror targetType = targetTypeHandle.resolve(wc);
if (targetType == null) {
//XXX: log
return ;
}
MethodTree mt = (MethodTree) tp.getLeaf();
TreeMaker make = wc.getTreeMaker();
wc.rewrite(mt.getReturnType(), make.Type(targetType));
}
示例14: createSetter
import com.sun.source.tree.MethodTree; //導入依賴的package包/類
/**
* Creates a setter method for a field.
*
* @param clazz the class to create the setter within
* @param field field to create setter for
* @return the setter method
* @since 0.20
*/
public MethodTree createSetter(TypeElement clazz, VariableElement field) {
assert clazz != null && field != null;
TreeMaker make = copy.getTreeMaker();
CodeStyle cs = DiffContext.getCodeStyle(copy);
Set<Modifier> mods = EnumSet.of(Modifier.PUBLIC);
boolean isStatic = field.getModifiers().contains(Modifier.STATIC);
if (isStatic) {
mods.add(Modifier.STATIC);
}
CharSequence name = field.getSimpleName();
assert name.length() > 0;
TypeMirror type = copy.getTypes().asMemberOf((DeclaredType)clazz.asType(), field);
String setterName = CodeStyleUtils.computeSetterName(field.getSimpleName(), isStatic, cs);
String paramName = addParamPrefixSuffix(removeFieldPrefixSuffix(field, cs), cs);
List<VariableTree> params = Collections.singletonList(make.Variable(make.Modifiers(EnumSet.noneOf(Modifier.class)), paramName, make.Type(type), null));
BlockTree body = make.Block(Collections.singletonList(make.ExpressionStatement(make.Assignment(make.MemberSelect(isStatic? make.Identifier(field.getEnclosingElement().getSimpleName()) : make.Identifier("this"), name), make.Identifier(paramName)))), false); //NOI18N
return make.Method(make.Modifiers(mods), setterName, make.Type(copy.getTypes().getNoType(TypeKind.VOID)), Collections.<TypeParameterTree>emptyList(), params, Collections.<ExpressionTree>emptyList(), body, null);
}
示例15: testCreateProperty
import com.sun.source.tree.MethodTree; //導入依賴的package包/類
public void testCreateProperty() throws Exception {
TestUtilities.copyStringToFileObject(testFO,
"package foo;" +
"public class TestClass {" +
" private Object x;" +
" public TestClass() {" +
" }" +
"}");
runModificationTask(testFO, new Task<WorkingCopy>() {
public void run(WorkingCopy copy) throws Exception {
GenerationUtils genUtils = GenerationUtils.newInstance(copy);
ClassTree classTree = (ClassTree)copy.getCompilationUnit().getTypeDecls().get(0);
TypeElement scope = SourceUtils.classTree2TypeElement(copy, classTree);
VariableTree field = genUtils.createField(scope, genUtils.createModifiers(Modifier.PRIVATE), "someProp", "java.lang.String", null);
MethodTree getter = genUtils.createPropertyGetterMethod(scope, genUtils.createModifiers(Modifier.PUBLIC), "someProp", "java.lang.String");
MethodTree setter = genUtils.createPropertySetterMethod(scope, genUtils.createModifiers(Modifier.PUBLIC), "someProp", "java.lang.String");
TreeMaker make = copy.getTreeMaker();
ClassTree newClassTree = classTree;
newClassTree = make.insertClassMember(newClassTree, 0, field);
newClassTree = make.addClassMember(newClassTree, getter);
newClassTree = make.addClassMember(newClassTree, setter);
copy.rewrite(classTree, newClassTree);
}
}).commit();
// TODO check the field and methods
}