org.eclipse.jdt.core.dom.MethodDeclaration#getBody ( )源码实例Demo

下面列出了org.eclipse.jdt.core.dom.MethodDeclaration#getBody ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: j2cl   文件: CompilationUnitBuilder.java
private Method convert(MethodDeclaration methodDeclaration) {
  List<Variable> parameters = new ArrayList<>();
  for (SingleVariableDeclaration parameter :
      JdtUtils.<SingleVariableDeclaration>asTypedList(methodDeclaration.parameters())) {
    parameters.add(createVariable(parameter));
  }

  MethodDescriptor methodDescriptor =
      JdtUtils.createMethodDescriptor(methodDeclaration.resolveBinding());

  // If a method has no body, initialize the body with an empty list of statements.
  Block body =
      methodDeclaration.getBody() == null
          ? Block.newBuilder().setSourcePosition(getSourcePosition(methodDeclaration)).build()
          : processEnclosedBy(methodDescriptor, () -> convert(methodDeclaration.getBody()));

  return newMethodBuilder(methodDescriptor)
      .setSourcePosition(getSourcePosition(methodDeclaration.getName()))
      .setParameters(parameters)
      .addStatements(body.getStatements())
      .build();
}
 
源代码2 项目: JDeodorant   文件: MethodDeclarationUtility.java
public static SimpleName isGetter(MethodDeclaration methodDeclaration) {
	Block methodBody = methodDeclaration.getBody();
	List<SingleVariableDeclaration> parameters = methodDeclaration.parameters();
	if(methodBody != null) {
		List<Statement> statements = methodBody.statements();
		if(statements.size() == 1 && parameters.size() == 0) {
			Statement statement = statements.get(0);
    		if(statement instanceof ReturnStatement) {
    			ReturnStatement returnStatement = (ReturnStatement)statement;
    			Expression returnStatementExpression = returnStatement.getExpression();
    			if(returnStatementExpression instanceof SimpleName) {
    				return (SimpleName)returnStatementExpression;
    			}
    			else if(returnStatementExpression instanceof FieldAccess) {
    				FieldAccess fieldAccess = (FieldAccess)returnStatementExpression;
    				return fieldAccess.getName();
    			}
    		}
		}
	}
	return null;
}
 
源代码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;
}
 
/**
 * 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;
}
 
@Override
public void updateBody(MethodDeclaration methodDeclaration, final CompilationUnitRewrite cuRewrite, RefactoringStatus result) throws CoreException {
	// ensure that the parameterObject is imported
	fParameterObjectFactory.createType(fCreateAsTopLevel, cuRewrite, methodDeclaration.getStartPosition());
	if (cuRewrite.getCu().equals(getCompilationUnit()) && !fParameterClassCreated) {
		createParameterClass(methodDeclaration, cuRewrite);
		fParameterClassCreated= true;
	}
	Block body= methodDeclaration.getBody();
	final List<SingleVariableDeclaration> parameters= methodDeclaration.parameters();
	if (body != null) { // abstract methods don't have bodies
		final ASTRewrite rewriter= cuRewrite.getASTRewrite();
		ListRewrite bodyStatements= rewriter.getListRewrite(body, Block.STATEMENTS_PROPERTY);
		List<ParameterInfo> managedParams= getParameterInfos();
		for (Iterator<ParameterInfo> iter= managedParams.iterator(); iter.hasNext();) {
			final ParameterInfo pi= iter.next();
			if (isValidField(pi)) {
				if (isReadOnly(pi, body, parameters, null)) {
					body.accept(new ASTVisitor(false) {

						@Override
						public boolean visit(SimpleName node) {
							updateSimpleName(rewriter, pi, node, parameters, cuRewrite.getCu().getJavaProject());
							return false;
						}

					});
					pi.setInlined(true);
				} else {
					ExpressionStatement initializer= fParameterObjectFactory.createInitializer(pi, getParameterName(), cuRewrite);
					bodyStatements.insertFirst(initializer, null);
				}
			}
		}
	}


}
 
源代码6 项目: JDeodorant   文件: ControlVariable.java
private static List<ASTNode> getAllVariableModifiersInParentMethod(SimpleName variable)
{
	List<ASTNode> bodyVariableModifiers = new ArrayList<ASTNode>();
	MethodDeclaration parentMethod = AbstractLoopUtilities.findParentMethodDeclaration(variable);
	if (parentMethod != null)
	{
		Block parentMethodBody = parentMethod.getBody();
		if (parentMethodBody != null)
		{
			ExpressionExtractor expressionExtractor = new ExpressionExtractor();
			bodyVariableModifiers.addAll(expressionExtractor.getVariableModifiers(parentMethodBody));
			// remove all variable updaters that are not modifying the specified variable or are after the position of the variable in use
			Iterator<ASTNode> it = bodyVariableModifiers.iterator();
			while (it.hasNext())
			{
				ASTNode currentNode = it.next();
				if (currentNode instanceof Expression)
				{
					Expression currentExpression = (Expression) currentNode;
					if (!AbstractLoopUtilities.isUpdatingVariable(currentExpression, variable) || currentExpression.getStartPosition() >= variable.getStartPosition())
					{
						it.remove();
					}
				}
			}
			// add the variable's declaration
			VariableDeclaration variableDeclaration = AbstractLoopUtilities.getVariableDeclaration(variable);
			if (variableDeclaration != null)
			{
				bodyVariableModifiers.add(0, variableDeclaration);
			}
		}
	}
	return bodyVariableModifiers;
}
 
@Override
public boolean visit(MethodDeclaration node) {
	Javadoc javadoc= node.getJavadoc();
	if (javadoc != null) {
		List<TagElement> tags= javadoc.tags();
		for (TagElement tag : tags) {
			String tagName= tag.getTagName();
			if (TagElement.TAG_EXCEPTION.equals(tagName) || TagElement.TAG_THROWS.equals(tagName)) {
				ASTNode name= (ASTNode) tag.fragments().get(0);
				if (name instanceof Name) {
					if (name != fSelectedNode && Bindings.equals(fException, ((Name) name).resolveBinding())) {
						fResult.add(new OccurrenceLocation(name.getStartPosition(), name.getLength(), 0, fDescription));
					}
				}
			}
		}
	}
	List<Type> thrownExceptionTypes= node.thrownExceptionTypes();
	for (Iterator<Type> iter= thrownExceptionTypes.iterator(); iter.hasNext(); ) {
		Type type = iter.next();
		if (type != fSelectedNode && Bindings.equals(fException, type.resolveBinding())) {
			fResult.add(new OccurrenceLocation(type.getStartPosition(), type.getLength(), 0, fDescription));
		}
	}
	Block body= node.getBody();
	if (body != null) {
		node.getBody().accept(this);
	}
	return false;
}
 
源代码8 项目: eclipse.jdt.ls   文件: DelegateMethodCreator.java
@Override
protected ASTNode createBody(BodyDeclaration bd) throws JavaModelException {

	MethodDeclaration methodDeclaration= (MethodDeclaration) bd;

	// interface or abstract method ? => don't create a method body.
	if (methodDeclaration.getBody() == null) {
		return null;
	}

	return createDelegateMethodBody(methodDeclaration);
}
 
源代码9 项目: eclipse.jdt.ls   文件: ExtractMethodAnalyzer.java
@Override
public boolean visit(MethodDeclaration node) {
	Block body = node.getBody();
	if (body == null) {
		return false;
	}
	Selection selection = getSelection();
	int nodeStart = body.getStartPosition();
	int nodeExclusiveEnd = nodeStart + body.getLength();
	// if selection node inside of the method body ignore method
	if (!(nodeStart < selection.getOffset() && selection.getExclusiveEnd() < nodeExclusiveEnd)) {
		return false;
	}
	return super.visit(node);
}
 
源代码10 项目: eclipse.jdt.ls   文件: ExtractFieldRefactoring.java
private void addFieldInitializationToConstructor(ASTRewrite rewrite, MethodDeclaration constructor) throws JavaModelException {
	if (constructor.getBody() == null) {
		constructor.setBody(fCURewrite.getAST().newBlock());
	}

	Statement newStatement = createNewAssignmentStatement();
	rewrite.getListRewrite(constructor.getBody(), Block.STATEMENTS_PROPERTY).insertLast(newStatement, null);
}
 
private boolean callsWritingConstructor(MethodDeclaration methodDeclaration, HashSet<IMethodBinding> writingConstructorBindings, Set<MethodDeclaration> visitedMethodDeclarations) {
	Block body= methodDeclaration.getBody();
	if (body == null)
		return false;

	List<Statement> statements= body.statements();
	if (statements.size() == 0)
		return false;

	Statement statement= statements.get(0);
	if (!(statement instanceof ConstructorInvocation))
		return false;

	ConstructorInvocation invocation= (ConstructorInvocation)statement;
	IMethodBinding constructorBinding= invocation.resolveConstructorBinding();
	if (constructorBinding == null)
		return false;

	if (writingConstructorBindings.contains(constructorBinding)) {
		return true;
	} else {
		ASTNode declaration= ASTNodes.findDeclaration(constructorBinding, methodDeclaration.getParent());
		if (!(declaration instanceof MethodDeclaration))
			return false;

		if (visitedMethodDeclarations.contains(declaration)) {
			return false;
		}
		visitedMethodDeclarations.add(methodDeclaration);
		return callsWritingConstructor((MethodDeclaration)declaration, writingConstructorBindings, visitedMethodDeclarations);
	}
}
 
private static boolean shouldInsertTempInitialization(MethodDeclaration constructor){
  	Assert.isTrue(constructor.isConstructor());
      if (constructor.getBody() == null)
      	return false;
      List<Statement> statements= constructor.getBody().statements();
      if (statements == null)
      	return false;
      if (statements.size() > 0 && statements.get(0) instanceof ConstructorInvocation)
      	return false;
return true;
  }
 
/**
 * Add modifier-related features.
 *
 * @param md
 * @param features
 */
private void addModifierFeatures(final MethodDeclaration md,
		final Set<String> features) {
	checkArgument(activeFeatures.contains(AvailableFeatures.MODIFIERS));
	JavaFeatureExtractor.addModifierFeatures(features, md.modifiers());

	if (md.getBody() == null) {
		features.add("isInterfaceDeclaration");
	}
}
 
源代码14 项目: txtUML   文件: SequenceDiagramVisitor.java
private void checkSendInRun(MethodDeclaration node) {
	final boolean showErrorHere = placeOfError == null;
	if (showErrorHere) {
		placeOfError = node.getBody();
	}
	checkSendInBlock(node.getBody(), showErrorHere);
	if (showErrorHere) {
		placeOfError = null;
	}
}
 
/**
 * Add modifier-related features.
 *
 * @param md
 * @param features
 */
private void addModifierFeatures(final MethodDeclaration md,
		final Set<String> features) {
	checkArgument(activeFeatures.contains(AvailableFeatures.MODIFIERS));
	JavaFeatureExtractor.addModifierFeatures(features, md.modifiers());

	if (md.getBody() == null) {
		features.add("isInterfaceDeclaration");
	}
}
 
/**
 * Add modifier-related features.
 *
 * @param md
 * @param features
 */
private void addModifierFeatures(final MethodDeclaration md,
		final Set<String> features) {
	checkArgument(activeFeatures.contains(AvailableFeatures.MODIFIERS));
	JavaFeatureExtractor.addModifierFeatures(features, md.modifiers());

	if (md.getBody() == null) {
		features.add("isInterfaceDeclaration");
	}
}
 
private static SuperConstructorInvocation getSuperConstructorCallNode(IMethod constructor, CompilationUnit cuNode) throws JavaModelException {
	Assert.isTrue(constructor.isConstructor());
	MethodDeclaration constructorNode= ASTNodeSearchUtil.getMethodDeclarationNode(constructor, cuNode);
	Assert.isTrue(constructorNode.isConstructor());
	Block body= constructorNode.getBody();
	Assert.isNotNull(body);
	List<Statement> statements= body.statements();
	if (! statements.isEmpty() && statements.get(0) instanceof SuperConstructorInvocation)
		return (SuperConstructorInvocation)statements.get(0);
	return null;
}
 
private boolean typeObjectGetterMethodAlreadyExists() {
	InheritanceTree tree = typeCheckElimination.getInheritanceTreeMatchingWithStaticTypes();
	if(tree != null) {
		MethodDeclaration[] contextMethods = sourceTypeDeclaration.getMethods();
		DefaultMutableTreeNode rootNode = tree.getRootNode();
		String rootClassName = (String)rootNode.getUserObject();
		DefaultMutableTreeNode leaf = rootNode.getFirstLeaf();
		List<String> subclassNames = new ArrayList<String>();
		while(leaf != null) {
			subclassNames.add((String)leaf.getUserObject());
			leaf = leaf.getNextLeaf();
		}
		for(MethodDeclaration contextMethod : contextMethods) {
			Type returnType = contextMethod.getReturnType2();
			if(returnType != null) {
				if(returnType.resolveBinding().getQualifiedName().equals(rootClassName)) {
					Block contextMethodBody = contextMethod.getBody();
					if(contextMethodBody != null) {
						List<Statement> statements = contextMethodBody.statements();
						if(statements.size() > 0 && statements.get(0) instanceof SwitchStatement) {
							SwitchStatement switchStatement = (SwitchStatement)statements.get(0);
							List<Statement> statements2 = switchStatement.statements();
							int matchCounter = 0;
							for(Statement statement2 : statements2) {
								if(statement2 instanceof ReturnStatement) {
									ReturnStatement returnStatement = (ReturnStatement)statement2;
									Expression returnStatementExpression = returnStatement.getExpression();
									if(returnStatementExpression instanceof ClassInstanceCreation) {
										ClassInstanceCreation classInstanceCreation = (ClassInstanceCreation)returnStatementExpression;
										Type classInstanceCreationType = classInstanceCreation.getType();
										if(subclassNames.contains(classInstanceCreationType.resolveBinding().getQualifiedName())) {
											matchCounter++;
										}
									}
								}
							}
							if(matchCounter == subclassNames.size())
								return true;
						}
					}
				}
			}
		}
	}
	return false;
}
 
源代码19 项目: eclipse.jdt.ls   文件: QuickAssistProcessor.java
private static boolean getAssignParamToFieldProposals(IInvocationContext context, ASTNode node, Collection<ChangeCorrectionProposal> resultingCollections) {
	node = ASTNodes.getNormalizedNode(node);
	ASTNode parent = node.getParent();
	if (!(parent instanceof SingleVariableDeclaration) || !(parent.getParent() instanceof MethodDeclaration)) {
		return false;
	}
	SingleVariableDeclaration paramDecl = (SingleVariableDeclaration) parent;
	IVariableBinding binding = paramDecl.resolveBinding();

	MethodDeclaration methodDecl = (MethodDeclaration) parent.getParent();
	if (binding == null || methodDecl.getBody() == null) {
		return false;
	}
	ITypeBinding typeBinding = binding.getType();
	if (typeBinding == null) {
		return false;
	}

	if (resultingCollections == null) {
		return true;
	}

	ITypeBinding parentType = Bindings.getBindingOfParentType(node);
	if (parentType != null) {
		if (parentType.isInterface()) {
			return false;
		}
		// assign to existing fields
		CompilationUnit root = context.getASTRoot();
		IVariableBinding[] declaredFields = parentType.getDeclaredFields();
		boolean isStaticContext = ASTResolving.isInStaticContext(node);
		for (int i = 0; i < declaredFields.length; i++) {
			IVariableBinding curr = declaredFields[i];
			if (isStaticContext == Modifier.isStatic(curr.getModifiers()) && typeBinding.isAssignmentCompatible(curr.getType())) {
				ASTNode fieldDeclFrag = root.findDeclaringNode(curr);
				if (fieldDeclFrag instanceof VariableDeclarationFragment) {
					VariableDeclarationFragment fragment = (VariableDeclarationFragment) fieldDeclFrag;
					if (fragment.getInitializer() == null) {
						resultingCollections.add(new AssignToVariableAssistProposal(context.getCompilationUnit(), paramDecl, fragment, typeBinding, IProposalRelevance.ASSIGN_PARAM_TO_EXISTING_FIELD));
					}
				}
			}
		}
	}

	AssignToVariableAssistProposal fieldProposal = new AssignToVariableAssistProposal(context.getCompilationUnit(), paramDecl, null, typeBinding, IProposalRelevance.ASSIGN_PARAM_TO_NEW_FIELD);
	resultingCollections.add(fieldProposal);
	return true;
}
 
/**
		 * {@inheritDoc}
		 */
		@Override
		public void rewriteAST(CompilationUnitRewrite cuRewrite, LinkedProposalModel model) throws CoreException {

			ASTRewrite rewrite= cuRewrite.getASTRewrite();
			ImportRemover importRemover= cuRewrite.getImportRemover();
			AST ast= rewrite.getAST();

			HashMap<ClassInstanceCreation, HashSet<String>> cicToNewNames= new HashMap<ClassInstanceCreation, HashSet<String>>();
			for (int i= 0; i < fExpressions.size(); i++) {
				ClassInstanceCreation classInstanceCreation= fExpressions.get(i);
				TextEditGroup group= createTextEditGroup(FixMessages.LambdaExpressionsFix_convert_to_lambda_expression, cuRewrite);

				AnonymousClassDeclaration anonymTypeDecl= classInstanceCreation.getAnonymousClassDeclaration();
				List<BodyDeclaration> bodyDeclarations= anonymTypeDecl.bodyDeclarations();

				Object object= bodyDeclarations.get(0);
				if (!(object instanceof MethodDeclaration))
					continue;
				MethodDeclaration methodDeclaration= (MethodDeclaration) object;
				HashSet<String> excludedNames= new HashSet<String>();
				if (i != 0) {
					for (ClassInstanceCreation convertedCic : fExpressions.subList(0, i)) {
						if (ASTNodes.isParent(classInstanceCreation, convertedCic)) {
							excludedNames.addAll(cicToNewNames.get(convertedCic));
						}
					}
				}
				HashSet<String> newNames= makeNamesUnique(excludedNames, methodDeclaration, rewrite, group);
				cicToNewNames.put(classInstanceCreation, new HashSet<String>(newNames));
				List<SingleVariableDeclaration> methodParameters= methodDeclaration.parameters();

				// use short form with inferred parameter types and without parentheses if possible
				LambdaExpression lambdaExpression= ast.newLambdaExpression();
				List<VariableDeclaration> lambdaParameters= lambdaExpression.parameters();
				lambdaExpression.setParentheses(methodParameters.size() != 1);
				for (SingleVariableDeclaration methodParameter : methodParameters) {
					VariableDeclarationFragment lambdaParameter= ast.newVariableDeclarationFragment();
					lambdaParameter.setName((SimpleName) rewrite.createCopyTarget(methodParameter.getName()));
					lambdaParameters.add(lambdaParameter);
				}
				
				Block body= methodDeclaration.getBody();
				List<Statement> statements= body.statements();
				ASTNode lambdaBody= body;
				if (statements.size() == 1) {
					// use short form with just an expression body if possible
					Statement statement= statements.get(0);
					if (statement instanceof ExpressionStatement) {
						lambdaBody= ((ExpressionStatement) statement).getExpression();
					} else if (statement instanceof ReturnStatement) {
						Expression returnExpression= ((ReturnStatement) statement).getExpression();
						if (returnExpression != null) {
							lambdaBody= returnExpression;
						}
					}
				}
				//TODO: Bug 421479: [1.8][clean up][quick assist] convert anonymous to lambda must consider lost scope of interface
//				lambdaBody.accept(new InterfaceAccessQualifier(rewrite, classInstanceCreation.getType().resolveBinding())); //TODO: maybe need a separate ASTRewrite and string placeholder
				
				lambdaExpression.setBody(rewrite.createCopyTarget(lambdaBody));
				Expression replacement= lambdaExpression;
				if (ASTNodes.isTargetAmbiguous(classInstanceCreation, lambdaParameters.isEmpty())) {
					CastExpression cast= ast.newCastExpression();
					cast.setExpression(lambdaExpression);
					ImportRewrite importRewrite= cuRewrite.getImportRewrite();
					ImportRewriteContext importRewriteContext= new ContextSensitiveImportRewriteContext(classInstanceCreation, importRewrite);
					Type castType= importRewrite.addImport(classInstanceCreation.getType().resolveBinding(), ast, importRewriteContext);
					cast.setType(castType);
					importRemover.registerAddedImports(castType);
					replacement= cast;
				}
				rewrite.replace(classInstanceCreation, replacement, group);

				importRemover.registerRemovedNode(classInstanceCreation);
				importRemover.registerRetainedNode(lambdaBody);
			}
		}