类org.eclipse.jdt.core.dom.MethodDeclaration源码实例Demo

下面列出了怎么用org.eclipse.jdt.core.dom.MethodDeclaration的API类实例代码及写法,或者点击链接到github查看源代码。

源代码1 项目: lapse-plus   文件: DeclarationInfoManager.java
public VariableDeclaration getVariableDeclaration(SimpleName name) {
	ASTNode node = name;
	do {
		node = node.getParent();
	} while ( node != null && !(node instanceof MethodDeclaration) );
	
	String key = null;
	
	if(node != null) {
		key = node.toString() + "/" + name.getFullyQualifiedName();
	}else {
		key = "GLOBAL" + name.getFullyQualifiedName();	
	}
	
	logError("Trying " + key);
	VariableDeclaration var = getVariableDeclaration(key);
	if(var == null && node != null) {
		key = "GLOBAL" + name.getFullyQualifiedName();
		log("Trying " + key);
		var = getVariableDeclaration(key);
	}
	
	return var;
}
 
源代码2 项目: JDeodorant   文件: MoveMethodRefactoring.java
private void removeAdditionalMethodsFromSourceClass() {
	Set<MethodDeclaration> methodsToBeMoved = new LinkedHashSet<MethodDeclaration>(additionalMethodsToBeMoved.values());
	for(MethodDeclaration methodDeclaration : methodsToBeMoved) {
		ASTRewrite sourceRewriter = ASTRewrite.create(sourceCompilationUnit.getAST());
		ListRewrite sourceClassBodyRewrite = sourceRewriter.getListRewrite(sourceTypeDeclaration, TypeDeclaration.BODY_DECLARATIONS_PROPERTY);
		sourceClassBodyRewrite.remove(methodDeclaration, null);
		try {
			TextEdit sourceEdit = sourceRewriter.rewriteAST();
			sourceMultiTextEdit.addChild(sourceEdit);
			sourceCompilationUnitChange.addTextEditGroup(new TextEditGroup("Remove additional moved method", new TextEdit[] {sourceEdit}));
		}
		catch(JavaModelException javaModelException) {
			javaModelException.printStackTrace();
		}
	}
}
 
源代码3 项目: JDeodorant   文件: TypeCheckingEvolution.java
private List<TypeCheckElimination> generateTypeCheckEliminationsWithinTypeDeclaration(TypeDeclaration typeDeclaration, TypeCheckElimination originalTypeCheckElimination) {
	List<TypeCheckElimination> typeCheckEliminations = new ArrayList<TypeCheckElimination>();
	for(MethodDeclaration method : typeDeclaration.getMethods()) {
		Block methodBody = method.getBody();
		if(methodBody != null) {
			List<TypeCheckElimination> list = generateTypeCheckEliminationsWithinMethodBody(methodBody);
			for(TypeCheckElimination typeCheckElimination : list) {
				if(!typeCheckElimination.allTypeCheckBranchesAreEmpty()) {
					TypeCheckCodeFragmentAnalyzer analyzer = new TypeCheckCodeFragmentAnalyzer(typeCheckElimination, typeDeclaration, method, null);
					if((typeCheckElimination.getTypeField() != null || typeCheckElimination.getTypeLocalVariable() != null || typeCheckElimination.getTypeMethodInvocation() != null) &&
							typeCheckElimination.allTypeCheckingsContainStaticFieldOrSubclassType() && typeCheckElimination.isApplicable()) {
						if(originalTypeCheckElimination.matchingStatesOrSubTypes(typeCheckElimination))
							typeCheckEliminations.add(typeCheckElimination);
					}
				}
			}
		}
	}
	return typeCheckEliminations;
}
 
@Override
protected List<SingleVariableDeclaration> computeParams(AST ast,
    MethodDeclaration srcMethod, MethodDeclaration dstMethod,
    ImportRewrite imports) {

  // Clone the sync method parameters
  List<SingleVariableDeclaration> params = new ArrayList<SingleVariableDeclaration>();
  params.addAll(JavaASTUtils.cloneParameters(ast, adjustSrcParams(srcMethod),
      imports));

  // Append an AsyncCallback
  params.add(Util.createAsyncCallbackParameter(ast,
      srcMethod.getReturnType2(), computeCallBackName(dstMethod), imports));

  return params;
}
 
源代码5 项目: apidiff   文件: MethodDiff.java
/**
 * Finding deprecated methods
 * 
 * @param version1
 * @param version2
 */
private void findAddedDeprecatedMethods(APIVersion version1, APIVersion version2) {
	
	for(TypeDeclaration typeVersion2 : version2.getApiAcessibleTypes()){
		for(MethodDeclaration methodVersion2 : typeVersion2.getMethods()){
			
			if(this.isMethodAcessible(methodVersion2) && this.isDeprecated(methodVersion2, typeVersion2)){
				MethodDeclaration methodInVersion1 = version1.findMethodByNameAndParametersAndReturn(methodVersion2, typeVersion2);
				if(methodInVersion1 == null || !this.isDeprecated(methodInVersion1, version1.getVersionAccessibleType(typeVersion2))){
					String description = this.description.deprecate(this.getSimpleNameMethod(methodVersion2), UtilTools.getPath(typeVersion2));
					this.addChange(typeVersion2, methodVersion2, Category.METHOD_DEPRECATED, false, description);
				}
			}
		}
	}
}
 
/**
 * Creates a new inline method refactoring
 * @param unit the compilation unit or class file
 * @param node the compilation unit node
 * @param selectionStart start
 * @param selectionLength length
 * @return returns the refactoring
 */
public static InlineMethodRefactoring create(ITypeRoot unit, CompilationUnit node, int selectionStart, int selectionLength) {
	ASTNode target= RefactoringAvailabilityTester.getInlineableMethodNode(unit, node, selectionStart, selectionLength);
	if (target == null)
		return null;
	if (target.getNodeType() == ASTNode.METHOD_DECLARATION) {

		return new InlineMethodRefactoring(unit, (MethodDeclaration)target, selectionStart, selectionLength);
	} else {
		ICompilationUnit cu= (ICompilationUnit) unit;
		if (target.getNodeType() == ASTNode.METHOD_INVOCATION) {
			return new InlineMethodRefactoring(cu, (MethodInvocation)target, selectionStart, selectionLength);
		} else if (target.getNodeType() == ASTNode.SUPER_METHOD_INVOCATION) {
			return new InlineMethodRefactoring(cu, (SuperMethodInvocation)target, selectionStart, selectionLength);
		} else if (target.getNodeType() == ASTNode.CONSTRUCTOR_INVOCATION) {
			return new InlineMethodRefactoring(cu, (ConstructorInvocation)target, selectionStart, selectionLength);
		}
	}
	return null;
}
 
源代码7 项目: JDeodorant   文件: MoveMethodRefactoring.java
private void addParamTagElementToJavadoc(MethodDeclaration newMethodDeclaration, ASTRewrite targetRewriter, String parameterToBeAdded) {
	if(newMethodDeclaration.getJavadoc() != null) {
		AST ast = newMethodDeclaration.getAST();
		Javadoc javadoc = newMethodDeclaration.getJavadoc();
		List<TagElement> tags = javadoc.tags();
		TagElement returnTagElement = null;
		for(TagElement tag : tags) {
			if(tag.getTagName() != null && tag.getTagName().equals(TagElement.TAG_RETURN)) {
				returnTagElement = tag;
				break;
			}
		}
		
		TagElement tagElement = ast.newTagElement();
		targetRewriter.set(tagElement, TagElement.TAG_NAME_PROPERTY, TagElement.TAG_PARAM, null);
		ListRewrite fragmentsRewrite = targetRewriter.getListRewrite(tagElement, TagElement.FRAGMENTS_PROPERTY);
		SimpleName paramName = ast.newSimpleName(parameterToBeAdded);
		fragmentsRewrite.insertLast(paramName, null);
		
		ListRewrite tagsRewrite = targetRewriter.getListRewrite(javadoc, Javadoc.TAGS_PROPERTY);
		if(returnTagElement != null)
			tagsRewrite.insertBefore(tagElement, returnTagElement, null);
		else
			tagsRewrite.insertLast(tagElement, null);
	}
}
 
/**
 * Returns the reserved identifiers in the method to move.
 *
 * @return the reserved identifiers
 * @throws JavaModelException
 *             if the method declaration could not be found
 */
protected String[] computeReservedIdentifiers() throws JavaModelException {
	final List<String> names= new ArrayList<String>();
	final MethodDeclaration declaration= ASTNodeSearchUtil.getMethodDeclarationNode(fMethod, fSourceRewrite.getRoot());
	if (declaration != null) {
		final List<SingleVariableDeclaration> parameters= declaration.parameters();
		VariableDeclaration variable= null;
		for (int index= 0; index < parameters.size(); index++) {
			variable= parameters.get(index);
			names.add(variable.getName().getIdentifier());
		}
		final Block body= declaration.getBody();
		if (body != null) {
			final IBinding[] bindings= new ScopeAnalyzer(fSourceRewrite.getRoot()).getDeclarationsAfter(body.getStartPosition(), ScopeAnalyzer.VARIABLES);
			for (int index= 0; index < bindings.length; index++)
				names.add(bindings[index].getName());
		}
	}
	final String[] result= new String[names.size()];
	names.toArray(result);
	return result;
}
 
源代码9 项目: JDeodorant   文件: MoveMethodRefactoring.java
private void removeParamTagElementFromJavadoc(MethodDeclaration newMethodDeclaration, ASTRewrite targetRewriter, String parameterToBeRemoved) {
	if(newMethodDeclaration.getJavadoc() != null) {
		Javadoc javadoc = newMethodDeclaration.getJavadoc();
		List<TagElement> tags = javadoc.tags();
		for(TagElement tag : tags) {
			if(tag.getTagName() != null && tag.getTagName().equals(TagElement.TAG_PARAM)) {
				List<ASTNode> tagFragments = tag.fragments();
				boolean paramFound = false;
				for(ASTNode node : tagFragments) {
					if(node instanceof SimpleName) {
						SimpleName simpleName = (SimpleName)node;
						if(simpleName.getIdentifier().equals(parameterToBeRemoved)) {
							paramFound = true;
							break;
						}
					}
				}
				if(paramFound) {
					ListRewrite tagsRewrite = targetRewriter.getListRewrite(javadoc, Javadoc.TAGS_PROPERTY);
					tagsRewrite.remove(tag, null);
					break;
				}
			}
		}
	}
}
 
/**
 * Finds and returns the <code>ASTNode</code> for the given source text
 * selection, if it is an entire constructor call or the class name portion
 * of a constructor call or constructor declaration, or null otherwise.
 * @param unit The compilation unit in which the selection was made
 * @param offset The textual offset of the start of the selection
 * @param length The length of the selection in characters
 * @return ClassInstanceCreation or MethodDeclaration
 */
private ASTNode getTargetNode(ICompilationUnit unit, int offset, int length) {
	ASTNode node= ASTNodes.getNormalizedNode(NodeFinder.perform(fCU, offset, length));
	if (node.getNodeType() == ASTNode.CLASS_INSTANCE_CREATION)
		return node;
	if (node.getNodeType() == ASTNode.METHOD_DECLARATION && ((MethodDeclaration)node).isConstructor())
		return node;
	// we have some sub node. Make sure its the right child of the parent
	StructuralPropertyDescriptor location= node.getLocationInParent();
	ASTNode parent= node.getParent();
	if (location == ClassInstanceCreation.TYPE_PROPERTY) {
		return parent;
	} else if (location == MethodDeclaration.NAME_PROPERTY && ((MethodDeclaration)parent).isConstructor()) {
		return parent;
	}
	return null;
}
 
源代码11 项目: JDeodorant   文件: ExpressionExtractor.java
private List<Expression> getExpressions(AnonymousClassDeclaration anonymousClassDeclaration) {
	List<Expression> expressionList = new ArrayList<Expression>();
	List<BodyDeclaration> bodyDeclarations = anonymousClassDeclaration.bodyDeclarations();
	for(BodyDeclaration bodyDeclaration : bodyDeclarations) {
		if(bodyDeclaration instanceof MethodDeclaration) {
			MethodDeclaration methodDeclaration = (MethodDeclaration)bodyDeclaration;
			Block body = methodDeclaration.getBody();
			if(body != null) {
				List<Statement> statements = body.statements();
				for(Statement statement : statements) {
					expressionList.addAll(getExpressions(statement));
				}
			}
		}
	}
	return expressionList;
}
 
源代码12 项目: JDeodorant   文件: MoveMethodRefactoring.java
private void modifySourceStaticMethodInvocationsInTargetClass(MethodDeclaration newMethodDeclaration, ASTRewrite targetRewriter) {
	ExpressionExtractor extractor = new ExpressionExtractor();	
	List<Expression> sourceMethodInvocations = extractor.getMethodInvocations(sourceMethod.getBody());
	List<Expression> newMethodInvocations = extractor.getMethodInvocations(newMethodDeclaration.getBody());
	int i = 0;
	for(Expression expression : sourceMethodInvocations) {
		if(expression instanceof MethodInvocation) {
			MethodInvocation methodInvocation = (MethodInvocation)expression;
			IMethodBinding methodBinding = methodInvocation.resolveMethodBinding();
			if((methodBinding.getModifiers() & Modifier.STATIC) != 0 &&
					methodBinding.getDeclaringClass().isEqualTo(sourceTypeDeclaration.resolveBinding()) &&
					!additionalMethodsToBeMoved.containsKey(methodInvocation)) {
				AST ast = newMethodDeclaration.getAST();
				SimpleName qualifier = ast.newSimpleName(sourceTypeDeclaration.getName().getIdentifier());
				targetRewriter.set(newMethodInvocations.get(i), MethodInvocation.EXPRESSION_PROPERTY, qualifier, null);
				this.additionalTypeBindingsToBeImportedInTargetClass.add(sourceTypeDeclaration.resolveBinding());
			}
		}
		i++;
	}
}
 
/**
 * Returns the bindings of the method argument types of the specified
 * declaration.
 *
 * @param declaration
 *            the method declaration
 * @return the array of method argument variable bindings
 */
protected static ITypeBinding[] getArgumentTypes(final MethodDeclaration declaration) {
	Assert.isNotNull(declaration);
	final IVariableBinding[] parameters= getArgumentBindings(declaration);
	final List<ITypeBinding> types= new ArrayList<ITypeBinding>(parameters.length);
	IVariableBinding binding= null;
	ITypeBinding type= null;
	for (int index= 0; index < parameters.length; index++) {
		binding= parameters[index];
		type= binding.getType();
		if (type != null)
			types.add(type);
	}
	final ITypeBinding[] result= new ITypeBinding[types.size()];
	types.toArray(result);
	return result;
}
 
源代码14 项目: JDeodorant   文件: MoveMethodRefactoring.java
private void replaceThisExpressionWithSourceClassParameterInMethodInvocationArguments(MethodDeclaration newMethodDeclaration, ASTRewrite targetRewriter) {
	ExpressionExtractor extractor = new ExpressionExtractor();
	List<Expression> methodInvocations = extractor.getMethodInvocations(newMethodDeclaration.getBody());
	for(Expression invocation : methodInvocations) {
		if(invocation instanceof MethodInvocation) {
			MethodInvocation methodInvocation = (MethodInvocation)invocation;
			List<Expression> arguments = methodInvocation.arguments();
			for(Expression argument : arguments) {
				if(argument instanceof ThisExpression) {
					SimpleName parameterName = null;
					if(!additionalArgumentsAddedToMovedMethod.contains("this")) {
						parameterName = addSourceClassParameterToMovedMethod(newMethodDeclaration, targetRewriter);
					}
					else {
						AST ast = newMethodDeclaration.getAST();
						String sourceTypeName = sourceTypeDeclaration.getName().getIdentifier();
						parameterName = ast.newSimpleName(sourceTypeName.replaceFirst(Character.toString(sourceTypeName.charAt(0)), Character.toString(Character.toLowerCase(sourceTypeName.charAt(0)))));
					}
					ListRewrite argumentRewrite = targetRewriter.getListRewrite(methodInvocation, MethodInvocation.ARGUMENTS_PROPERTY);
					argumentRewrite.replace(argument, parameterName, null);
				}
			}
		}
	}
}
 
/**
 * Add argument-related features.
 *
 * @param md
 * @param features
 */
private void addArgumentFeatures(final MethodDeclaration md,
		final Set<String> features) {
	checkArgument(activeFeatures.contains(AvailableFeatures.ARGUMENTS));
	features.add("nParams:" + md.parameters().size());
	for (int i = 0; i < md.parameters().size(); i++) {
		final SingleVariableDeclaration varDecl = (SingleVariableDeclaration) md
				.parameters().get(i);
		features.add("param" + i + "Type:" + varDecl.getType().toString());
		for (final String namepart : JavaFeatureExtractor
				.getNameParts(varDecl.getName().toString())) {
			features.add("paramName:" + namepart);
		}
	}

	if (md.isVarargs()) {
		features.add("isVarArg");
	}
}
 
private static ASTNode getInlineableMethodNode(ASTNode node, IJavaElement unit) {
	if (node == null)
		return null;
	switch (node.getNodeType()) {
		case ASTNode.SIMPLE_NAME:
			StructuralPropertyDescriptor locationInParent= node.getLocationInParent();
			if (locationInParent == MethodDeclaration.NAME_PROPERTY) {
				return node.getParent();
			} else if (locationInParent == MethodInvocation.NAME_PROPERTY
					|| locationInParent == SuperMethodInvocation.NAME_PROPERTY) {
				return unit instanceof ICompilationUnit ? node.getParent() : null; // don't start on invocations in binary
			}
			return null;
		case ASTNode.EXPRESSION_STATEMENT:
			node= ((ExpressionStatement)node).getExpression();
	}
	switch (node.getNodeType()) {
		case ASTNode.METHOD_DECLARATION:
			return node;
		case ASTNode.METHOD_INVOCATION:
		case ASTNode.SUPER_METHOD_INVOCATION:
		case ASTNode.CONSTRUCTOR_INVOCATION:
			return unit instanceof ICompilationUnit ? node : null; // don't start on invocations in binary
	}
	return null;
}
 
public static List<IJavaCompletionProposal> createProposalsForProblemOnAsyncType(
    ICompilationUnit asyncCompilationUnit, ASTNode problemNode,
    String syncMethodBindingKey) {
  TypeDeclaration asyncTypeDecl = (TypeDeclaration) ASTResolving.findAncestor(
      problemNode, ASTNode.TYPE_DECLARATION);
  assert (asyncTypeDecl != null);
  String asyncQualifiedTypeName = asyncTypeDecl.resolveBinding().getQualifiedName();

  // Lookup the sync version of the interface
  IType syncType = RemoteServiceUtilities.findSyncType(asyncTypeDecl);
  if (syncType == null) {
    return Collections.emptyList();
  }

  MethodDeclaration syncMethodDecl = JavaASTUtils.findMethodDeclaration(
      syncType.getCompilationUnit(), syncMethodBindingKey);
  if (syncMethodDecl == null) {
    return Collections.emptyList();
  }

  return Collections.<IJavaCompletionProposal> singletonList(new CreateAsyncMethodProposal(
      asyncCompilationUnit, asyncQualifiedTypeName, syncMethodDecl));
}
 
private boolean isWrittenInTypeConstructors(List<SimpleName> writes, ITypeBinding declaringClass) {

			for (int i= 0; i < writes.size(); i++) {
	            SimpleName name= writes.get(i);

	            MethodDeclaration methodDeclaration= getWritingConstructor(name);
	            if (methodDeclaration == null)
	            	return false;

	            if (!methodDeclaration.isConstructor())
	            	return false;

	            IMethodBinding constructor= methodDeclaration.resolveBinding();
	            if (constructor == null)
	            	return false;

	            ITypeBinding declaringClass2= constructor.getDeclaringClass();
	            if (!declaringClass.equals(declaringClass2))
	            	return false;
            }

	        return true;
        }
 
/**
 * @param node
 * @return
 */
public boolean methodOverrides(final MethodDeclaration node) {
	final boolean hasAnnotation = MethodUtils
			.hasOverrideAnnotation(node);
	final boolean isOverride = pti.isMethodOverride(className.peek(),
			node);
	return hasAnnotation || isOverride;
}
 
源代码20 项目: api-mining   文件: MethodRetriever.java
public static Map<String, MethodDeclaration> getMethodNodes(final File file)
		throws IOException {
	final JavaASTExtractor astExtractor = new JavaASTExtractor(false);
	final MethodRetriever m = new MethodRetriever();
	final CompilationUnit cu = astExtractor.getAST(file);
	cu.accept(m);
	return m.methods;
}
 
@Override
@SuppressWarnings("unchecked")
protected List<SingleVariableDeclaration> adjustSrcParams(
    MethodDeclaration method) {

  // The source method is in the sync interface
  return method.parameters();
}
 
/**
 * Add exception related features.
 *
 * @param md
 * @param features
 */
private void addExceptionFeatures(final MethodDeclaration md,
		final Set<String> features) {
	checkArgument(activeFeatures.contains(AvailableFeatures.EXCEPTIONS));
	for (final Object exception : md.thrownExceptionTypes()) {
		final SimpleType ex = (SimpleType) exception;
		features.add("thrownException:" + ex.toString());
	}
}
 
protected void updateVariableReferences(ASTRewrite rewrite, ClassInstanceCreation classLoaderCreation) {
    Assert.isNotNull(rewrite);
    Assert.isNotNull(classLoaderCreation);

    MethodDeclaration method = findMethodDeclaration(classLoaderCreation);
    if (method != null) {
        final Set<String> variableReferences = findVariableReferences(classLoaderCreation.arguments());
        if (!variableReferences.isEmpty()) {
            updateMethodParams(rewrite, variableReferences, method.parameters());
            updateLocalVariableDeclarations(rewrite, variableReferences, method.getBody());
        }
    }
}
 
源代码24 项目: codemining-core   文件: MethodExtractor.java
public static List<MethodDeclaration> getMethods(final File file, final ProjectTypeInformation pti)
		throws IOException {
	try {
		final JavaASTExtractor ex = new JavaASTExtractor(false);
		final MethodVisitor mv = new MethodVisitor(pti);
		final CompilationUnit cu = ex.getAST(file);
		cu.accept(mv);
		return mv.allMethods;
	} catch (Exception e) {
		System.err.println(ExceptionUtils.getFullStackTrace(e));
	}
	return new ArrayList<>();
}
 
@Override
protected ASTRewrite getRewrite() throws CoreException {
	CompilationUnit astRoot= (CompilationUnit) fInvocationNode.getRoot();
	ASTNode methodDecl= astRoot.findDeclaringNode(fSenderBinding);
	ASTNode newMethodDecl= null;
	if (methodDecl != null) {
		newMethodDecl= methodDecl;
	} else {
		astRoot= ASTResolving.createQuickFixAST(getCompilationUnit(), null);
		newMethodDecl= astRoot.findDeclaringNode(fSenderBinding.getKey());
	}
	createImportRewrite(astRoot);

	if (newMethodDecl instanceof MethodDeclaration) {
		MethodDeclaration decl= (MethodDeclaration) newMethodDecl;

		ASTRewrite rewrite= ASTRewrite.create(astRoot.getAST());
		if (fParameterChanges != null) {
			modifyParameters(rewrite, decl);
		}
		if (fExceptionChanges != null) {
			modifyExceptions(rewrite, decl);
		}
		return rewrite;
	}
	return null;
}
 
源代码26 项目: compiler   文件: TestQ21.java
@Override
public boolean visit(AnonymousClassDeclaration node) {
//	classes++;
	for (Object d : node.bodyDeclarations()) {
		if (d instanceof FieldDeclaration)
			((FieldDeclaration)d).accept(this);
		if (d instanceof MethodDeclaration)
			((MethodDeclaration)d).accept(this);
	}
	return false;
}
 
protected void copyParameters(final ASTRewrite rewrite, final ICompilationUnit unit, final MethodDeclaration oldMethod, final MethodDeclaration newMethod, final TypeVariableMaplet[] mapping) throws JavaModelException {
	SingleVariableDeclaration newDeclaration= null;
	for (int index= 0, size= oldMethod.parameters().size(); index < size; index++) {
		final SingleVariableDeclaration oldDeclaration= (SingleVariableDeclaration) oldMethod.parameters().get(index);
		if (mapping.length > 0)
			newDeclaration= createPlaceholderForSingleVariableDeclaration(oldDeclaration, unit, mapping, rewrite);
		else
			newDeclaration= createPlaceholderForSingleVariableDeclaration(oldDeclaration, unit, rewrite);
		newMethod.parameters().add(newDeclaration);
	}
}
 
源代码28 项目: naturalize   文件: DynamicRangeEval.java
private void pushStatsFor(final BaseIdentifierRenamings renamer,
		final MethodDeclaration method, final AbstractNGramLM lm,
		final List<String> allToks) throws IOException {
	final JavaASTExtractor ex = new JavaASTExtractor(false);
	final Multimap<Scope, String> scopes = scopeExtractor
			.getFromNode(method);
	final ScopedIdentifierRenaming identifierRenamer = new ScopedIdentifierRenaming(
			scopeExtractor, ParseType.METHOD);
	final List<String> renamedVars = Lists.newArrayList(scopes.values());
	Collections.shuffle(renamedVars);

	checkArgument(!renamedVars.isEmpty());

	final SnippetSuggestions ssBefore = SnippetScorer.scoreSnippet(method,
			renamer, scopeExtractor, false, false);

	final Map<String, String> renamingPlan = Maps.newTreeMap();
	final String targetName = getRandomName(allToks, renamer.getLM()
			.getTokenizer());
	renamingPlan.put(renamedVars.get(0), targetName);

	final String renamedMethod = identifierRenamer.getRenamedCode(
			method.toString(), method.toString(), renamingPlan);
	final ASTNode renamedMethodNode = ex.getASTNode(renamedMethod,
			ParseType.METHOD);

	final SnippetSuggestions ssAfter = SnippetScorer.scoreSnippet(
			renamedMethodNode, renamer, scopeExtractor, false, false);

	scoreBest.add(new BeforeAfterScore<Double>(-ssBefore.suggestions
			.first().getConfidence(), -ssAfter.suggestions.first()
			.getConfidence()));

	if (DEBUG_OUTPUT) {
		printDebugOutput(method, lm, renamedVars, ssBefore, targetName,
				renamedMethodNode, ssAfter);
	}
}
 
protected void copyReturnType(final ASTRewrite rewrite, final ICompilationUnit unit, final MethodDeclaration oldMethod, final MethodDeclaration newMethod, final TypeVariableMaplet[] mapping) throws JavaModelException {
	Type newReturnType= null;
	if (mapping.length > 0)
		newReturnType= createPlaceholderForType(oldMethod.getReturnType2(), unit, mapping, rewrite);
	else
		newReturnType= createPlaceholderForType(oldMethod.getReturnType2(), unit, rewrite);
	newMethod.setReturnType2(newReturnType);
}
 
private MethodDeclaration createGetterMethod(AST ast, ASTRewrite rewriter, String lineDelimiter) throws CoreException {
	FieldDeclaration field = ASTNodes.getParent(fFieldDeclaration, FieldDeclaration.class);
	Type type = field.getType();
	MethodDeclaration result = ast.newMethodDeclaration();
	result.setName(ast.newSimpleName(fGetterName));
	result.modifiers().addAll(ASTNodeFactory.newModifiers(ast, createModifiers()));
	Type returnType = DimensionRewrite.copyTypeAndAddDimensions(type, fFieldDeclaration.extraDimensions(), rewriter);
	result.setReturnType2(returnType);

	Block block = ast.newBlock();
	result.setBody(block);

	String body = CodeGeneration.getGetterMethodBodyContent(fField.getCompilationUnit(), getTypeName(field.getParent()), fGetterName, fField.getElementName(), lineDelimiter);
	if (body != null) {
		body = body.substring(0, body.lastIndexOf(lineDelimiter));
		ASTNode getterNode = rewriter.createStringPlaceholder(body, ASTNode.BLOCK);
		block.statements().add(getterNode);
	} else {
		ReturnStatement rs = ast.newReturnStatement();
		rs.setExpression(ast.newSimpleName(fField.getElementName()));
		block.statements().add(rs);
	}
	if (fGenerateJavadoc) {
		String string = CodeGeneration.getGetterComment(fField.getCompilationUnit(), getTypeName(field.getParent()), fGetterName, fField.getElementName(), ASTNodes.asString(type), StubUtility.getBaseName(fField), lineDelimiter);
		if (string != null) {
			Javadoc javadoc = (Javadoc) fRewriter.createStringPlaceholder(string, ASTNode.JAVADOC);
			result.setJavadoc(javadoc);
		}
	}
	return result;
}
 
 类所在包
 同包方法