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

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

源代码1 项目: eclipse.jdt.ls   文件: JavadocTagsSubProcessor.java
public static void getInvalidQualificationProposals(IInvocationContext context, IProblemLocationCore problem,
		Collection<ChangeCorrectionProposal> proposals) {
	ASTNode node= problem.getCoveringNode(context.getASTRoot());
	if (!(node instanceof Name)) {
		return;
	}
	Name name= (Name) node;
	IBinding binding= name.resolveBinding();
	if (!(binding instanceof ITypeBinding)) {
		return;
	}
	ITypeBinding typeBinding= (ITypeBinding)binding;

	AST ast= node.getAST();
	ASTRewrite rewrite= ASTRewrite.create(ast);
	rewrite.replace(name, ast.newName(typeBinding.getQualifiedName()), null);

	String label= CorrectionMessages.JavadocTagsSubProcessor_qualifylinktoinner_description;
	ASTRewriteCorrectionProposal proposal = new ASTRewriteCorrectionProposal(label, CodeActionKind.QuickFix, context.getCompilationUnit(),
			rewrite, IProposalRelevance.QUALIFY_INNER_TYPE_NAME);

	proposals.add(proposal);
}
 
/**
 * Creates the new <CODE>InfixExpression</CODE> <CODE>(x &amp; 1) == 1</CODE>.
 */
@Override
protected InfixExpression createCorrectOddnessCheck(ASTRewrite rewrite, Expression numberExpression) {
    Assert.isNotNull(rewrite);
    Assert.isNotNull(numberExpression);

    final AST ast = rewrite.getAST();
    InfixExpression andOddnessCheck = ast.newInfixExpression();
    ParenthesizedExpression parenthesizedExpression = ast.newParenthesizedExpression();
    InfixExpression andExpression = ast.newInfixExpression();

    andExpression.setLeftOperand((Expression) rewrite.createMoveTarget(numberExpression));
    andExpression.setOperator(AND);
    andExpression.setRightOperand(ast.newNumberLiteral("1"));
    parenthesizedExpression.setExpression(andExpression);
    andOddnessCheck.setLeftOperand(parenthesizedExpression);
    andOddnessCheck.setOperator(EQUALS);
    andOddnessCheck.setRightOperand(ast.newNumberLiteral("1"));

    return andOddnessCheck;

}
 
private void createStateField() {
	ASTRewrite sourceRewriter = ASTRewrite.create(sourceTypeDeclaration.getAST());
	AST contextAST = sourceTypeDeclaration.getAST();
	ListRewrite contextBodyRewrite = sourceRewriter.getListRewrite(sourceTypeDeclaration, TypeDeclaration.BODY_DECLARATIONS_PROPERTY);
	VariableDeclarationFragment typeFragment = createStateFieldVariableDeclarationFragment(sourceRewriter, contextAST);
	
	FieldDeclaration typeFieldDeclaration = contextAST.newFieldDeclaration(typeFragment);
	sourceRewriter.set(typeFieldDeclaration, FieldDeclaration.TYPE_PROPERTY, contextAST.newSimpleName(abstractClassName), null);
	ListRewrite typeFieldDeclarationModifiersRewrite = sourceRewriter.getListRewrite(typeFieldDeclaration, FieldDeclaration.MODIFIERS2_PROPERTY);
	typeFieldDeclarationModifiersRewrite.insertLast(contextAST.newModifier(Modifier.ModifierKeyword.PRIVATE_KEYWORD), null);
	contextBodyRewrite.insertBefore(typeFieldDeclaration, typeCheckElimination.getTypeField().getParent(), null);
	
	try {
		TextEdit sourceEdit = sourceRewriter.rewriteAST();
		ICompilationUnit sourceICompilationUnit = (ICompilationUnit)sourceCompilationUnit.getJavaElement();
		CompilationUnitChange change = compilationUnitChanges.get(sourceICompilationUnit);
		change.getEdit().addChild(sourceEdit);
		change.addTextEditGroup(new TextEditGroup("Create field holding the current state", new TextEdit[] {sourceEdit}));
	} catch (JavaModelException e) {
		e.printStackTrace();
	}
}
 
protected void updateImportDeclarations(ASTRewrite rewrite, CompilationUnit compilationUnit) {
    Assert.isNotNull(rewrite);
    Assert.isNotNull(compilationUnit);

    if (isUpdateImports()) {
        final AST ast = rewrite.getAST();
        SortedSet<ImportDeclaration> imports = new TreeSet<>(importComparator);
        imports.add(createImportDeclaration(ast, PrivilegedAction.class));
        if (!isStaticImport()) {
            imports.add(createImportDeclaration(ast, AccessController.class));
        } else {
            imports.add(createImportDeclaration(ast, AccessController.class, DO_PRIVILEGED_METHOD_NAME));
        }
        addImports(rewrite, compilationUnit, imports);
    }
}
 
/**
 * {@inheritDoc}
 */
@Override
public void rewriteAST(CompilationUnitRewrite cuRewrite, LinkedProposalModel model) throws CoreException {
	TextEditGroup group= createTextEditGroup(FixMessages.TypeParametersFix_insert_inferred_type_arguments_description, cuRewrite);

	ASTRewrite rewrite= cuRewrite.getASTRewrite();
	ImportRewrite importRewrite= cuRewrite.getImportRewrite();
	AST ast= cuRewrite.getRoot().getAST();

	for (int i= 0; i < fCreatedTypes.length; i++) {
		ParameterizedType createdType= fCreatedTypes[i];

		ITypeBinding[] typeArguments= createdType.resolveBinding().getTypeArguments();
		ContextSensitiveImportRewriteContext importContext= new ContextSensitiveImportRewriteContext(cuRewrite.getRoot(), createdType.getStartPosition(), importRewrite);

		ListRewrite argumentsRewrite= rewrite.getListRewrite(createdType, ParameterizedType.TYPE_ARGUMENTS_PROPERTY);
		for (int j= 0; j < typeArguments.length; j++) {
			ITypeBinding typeArgument= typeArguments[j];
			Type argumentNode= importRewrite.addImport(typeArgument, ast, importContext);
			argumentsRewrite.insertLast(argumentNode, group);
		}
	}
}
 
/**
 * Generates a sync/async method declaration based on the associated
 * async/sync method signature.
 */
private MethodDeclaration computeMethodSignature(AST ast, RpcPair rpcPair,
    MethodDeclaration dstMethod) {

  MethodDeclaration method = ast.newMethodDeclaration();

  // New method has same name as original
  String methodName = rpcPair.srcMethod.getName().getIdentifier();
  method.setName(ast.newSimpleName(methodName));

  // Update the parameters
  @SuppressWarnings("unchecked")
  List<SingleVariableDeclaration> params = method.parameters();
  params.addAll(computeParams(ast, rpcPair.srcMethod, dstMethod,
      getImportRewrite()));

  // Update the return type
  method.setReturnType2(computeReturnType(ast, rpcPair.srcMethod, dstMethod,
      getImportRewrite()));

  return method;
}
 
@Override
protected ASTRewrite getRewrite() {
	AST ast= fCallerNode.getAST();
	ASTRewrite rewrite= ASTRewrite.create(ast);
	ChildListPropertyDescriptor property= getProperty();

	for (int i= 0; i < fInsertIndexes.length; i++) {
		int idx= fInsertIndexes[i];
		String key= "newarg_" + i; //$NON-NLS-1$
		Expression newArg= evaluateArgumentExpressions(ast, fParamTypes[idx], key);
		ListRewrite listRewriter= rewrite.getListRewrite(fCallerNode, property);
		listRewriter.insertAt(newArg, idx, null);

		addLinkedPosition(rewrite.track(newArg), i == 0, key);
	}
	return rewrite;
}
 
源代码8 项目: eclipse.jdt.ls   文件: DimensionRewrite.java
/**
 * Creates a {@link ASTRewrite#createCopyTarget(ASTNode) copy} of <code>type</code>
 * and adds <code>extraDimensions</code> to it.
 *
 * @param type the type to copy
 * @param extraDimensions the dimensions to add
 * @param rewrite the ASTRewrite with which to create new nodes
 * @return the copy target with added dimensions
 */
public static Type copyTypeAndAddDimensions(Type type, List<Dimension> extraDimensions, ASTRewrite rewrite) {
	AST ast= rewrite.getAST();
	if (extraDimensions.isEmpty()) {
		return (Type) rewrite.createCopyTarget(type);
	}

	ArrayType result;
	if (type instanceof ArrayType) {
		ArrayType arrayType= (ArrayType) type;
		Type varElementType= (Type) rewrite.createCopyTarget(arrayType.getElementType());
		result= ast.newArrayType(varElementType, 0);
		result.dimensions().addAll(copyDimensions(extraDimensions, rewrite));
		result.dimensions().addAll(copyDimensions(arrayType.dimensions(), rewrite));
	} else {
		Type elementType= (Type) rewrite.createCopyTarget(type);
		result= ast.newArrayType(elementType, 0);
		result.dimensions().addAll(copyDimensions(extraDimensions, rewrite));
	}
	return result;
}
 
public void generateBuilder(CompilationUnitModificationDomain compilationUnitModificationDomain, RegularBuilderUserPreference preference) {
    // TODO: replace parameters, where these go separately with compilation modification domain
    AST ast = compilationUnitModificationDomain.getAst();
    ListRewrite listRewrite = compilationUnitModificationDomain.getListRewrite();
    TypeDeclaration originalType = compilationUnitModificationDomain.getOriginalType();

    builderRemover.removeExistingBuilderWhenNeeded(compilationUnitModificationDomain);

    TypeDeclaration builderType = regularBuilderClassCreator.createBuilderClass(ast, originalType, preference);
    defaultConstructorAppender.addDefaultConstructorIfNeeded(compilationUnitModificationDomain, preference.getBuilderFields());
    privateConstructorPopulator.addPrivateConstructorToCompilationUnit(ast, originalType, builderType, listRewrite, preference.getBuilderFields());
    builderMethodPopulator.addBuilderMethodToCompilationUnit(ast, listRewrite, originalType, builderType, preference);
    instanceCopyBuilderMethodPopulator.addInstanceCopyBuilderMethodToCompilationUnitIfNeeded(compilationUnitModificationDomain, builderType, preference);

    listRewrite.insertLast(builderType, null);

    globalBuilderPostProcessor.postProcessBuilder(compilationUnitModificationDomain, builderType);

    importPopulator.populateImports(compilationUnitModificationDomain);
}
 
private SimpleName getNewName(ASTRewrite rewrite) {
	AST ast= rewrite.getAST();
	String name;
	if (fInvocationNode.getLocationInParent() == MemberValuePair.NAME_PROPERTY) {
		name= ((SimpleName) fInvocationNode).getIdentifier();
		if (ast == fInvocationNode.getAST()) {
			addLinkedPosition(rewrite.track(fInvocationNode), true, KEY_NAME);
		}
	} else {
		name= "value"; //$NON-NLS-1$
	}


	SimpleName newNameNode= ast.newSimpleName(name);
	addLinkedPosition(rewrite.track(newNameNode), false, KEY_NAME);
	return newNameNode;
}
 
private void addInitializersToConstructors(ASTRewrite rewrite) throws CoreException {
 	Assert.isTrue(! isDeclaredInAnonymousClass());
 	final AbstractTypeDeclaration declaration= (AbstractTypeDeclaration)getMethodDeclaration().getParent();
 	final MethodDeclaration[] constructors= getAllConstructors(declaration);
 	if (constructors.length == 0) {
 		AST ast= rewrite.getAST();
 		MethodDeclaration newConstructor= ast.newMethodDeclaration();
 		newConstructor.setConstructor(true);
 		newConstructor.modifiers().addAll(ast.newModifiers(declaration.getModifiers() & ModifierRewrite.VISIBILITY_MODIFIERS));
 		newConstructor.setName(ast.newSimpleName(declaration.getName().getIdentifier()));
 		newConstructor.setJavadoc(getNewConstructorComment(rewrite));
 		newConstructor.setBody(ast.newBlock());

 		addFieldInitializationToConstructor(rewrite, newConstructor);

 		int insertionIndex= computeInsertIndexForNewConstructor(declaration);
rewrite.getListRewrite(declaration, declaration.getBodyDeclarationsProperty()).insertAt(newConstructor, insertionIndex, null);
 	} else {
 		for (int index= 0; index < constructors.length; index++) {
             if (shouldInsertTempInitialization(constructors[index]))
                 addFieldInitializationToConstructor(rewrite, constructors[index]);
         }
 	}
 }
 
private static boolean getAddFinallyProposals(IInvocationContext context, ASTNode node, Collection<ICommandAccess> resultingCollections) {
	TryStatement tryStatement= ASTResolving.findParentTryStatement(node);
	if (tryStatement == null || tryStatement.getFinally() != null) {
		return false;
	}
	Statement statement= ASTResolving.findParentStatement(node);
	if (tryStatement != statement && tryStatement.getBody() != statement) {
		return false; // an node inside a catch or finally block
	}

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

	AST ast= tryStatement.getAST();
	ASTRewrite rewrite= ASTRewrite.create(ast);
	Block finallyBody= ast.newBlock();

	rewrite.set(tryStatement, TryStatement.FINALLY_PROPERTY, finallyBody, null);

	String label= CorrectionMessages.QuickAssistProcessor_addfinallyblock_description;
	Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_ADD);
	ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, IProposalRelevance.ADD_FINALLY_BLOCK, image);
	resultingCollections.add(proposal);
	return true;
}
 
源代码13 项目: sahagin-java   文件: SrcTreeGenerator.java
private static void parseAST(String[] srcFiles, Charset srcCharset,
        String[] classPathEntries, FileASTRequestor requestor) {
    ASTParser parser = ASTParser.newParser(AST.JLS8);
    Map<String, String> options = JavaCore.getOptions();
    JavaCore.setComplianceOptions(JavaCore.VERSION_1_8, options);
    parser.setCompilerOptions(options);
    parser.setKind(ASTParser.K_COMPILATION_UNIT);
    parser.setResolveBindings(true);
    parser.setBindingsRecovery(true);
    parser.setEnvironment(classPathEntries, null, null, true);
    String[] srcEncodings = new String[srcFiles.length];
    for (int i = 0; i < srcEncodings.length; i++) {
        srcEncodings[i] = srcCharset.name();
    }
    parser.createASTs(
            srcFiles, srcEncodings, new String[]{}, requestor, null);
}
 
@Override
protected Expression computeProposals(AST ast, ITypeBinding returnBinding, int returnOffset, CompilationUnit root, Expression result) {
	ScopeAnalyzer analyzer= new ScopeAnalyzer(root);
	IBinding[] bindings= analyzer.getDeclarationsInScope(returnOffset, ScopeAnalyzer.VARIABLES | ScopeAnalyzer.CHECK_VISIBILITY);

	org.eclipse.jdt.core.dom.NodeFinder finder= new org.eclipse.jdt.core.dom.NodeFinder(root, returnOffset, 0);
	ASTNode varDeclFrag= ASTResolving.findAncestor(finder.getCoveringNode(), ASTNode.VARIABLE_DECLARATION_FRAGMENT);
	IVariableBinding varDeclFragBinding= null;
	if (varDeclFrag != null)
		varDeclFragBinding= ((VariableDeclarationFragment) varDeclFrag).resolveBinding();
	for (int i= 0; i < bindings.length; i++) {
		IVariableBinding curr= (IVariableBinding) bindings[i];
		ITypeBinding type= curr.getType();
		// Bindings are compared to make sure that a lambda does not return a variable which is yet to be initialised.
		if (type != null && type.isAssignmentCompatible(returnBinding) && testModifier(curr) && !Bindings.equals(curr, varDeclFragBinding)) {
			if (result == null) {
				result= ast.newSimpleName(curr.getName());
			}
			addLinkedPositionProposal(RETURN_EXPRESSION_KEY, curr.getName(), null);
		}
	}
	return result;
}
 
public ITypeBinding getTypeBinding(AST ast) {
	boolean couldBeObject= false;
	for (int i= 0; i < fResult.size(); i++) {
		ReturnStatement node= fResult.get(i);
		Expression expr= node.getExpression();
		if (expr != null) {
			ITypeBinding binding= Bindings.normalizeTypeBinding(expr.resolveTypeBinding());
			if (binding != null) {
				return binding;
			} else {
				couldBeObject= true;
			}
		} else {
			return ast.resolveWellKnownType("void"); //$NON-NLS-1$
		}
	}
	if (couldBeObject) {
		return ast.resolveWellKnownType("java.lang.Object"); //$NON-NLS-1$
	}
	return ast.resolveWellKnownType("void"); //$NON-NLS-1$
}
 
private static Statement createAssignmentStatement(ASTRewrite rewrite, Assignment.Operator assignmentOperator, Expression origAssignee, Expression origAssigned) {
	AST ast= rewrite.getAST();
	Assignment elseAssignment= ast.newAssignment();
	elseAssignment.setOperator(assignmentOperator);
	elseAssignment.setLeftHandSide((Expression) rewrite.createCopyTarget(origAssignee));
	elseAssignment.setRightHandSide((Expression) rewrite.createCopyTarget(origAssigned));
	ExpressionStatement statement= ast.newExpressionStatement(elseAssignment);
	return statement;
}
 
源代码17 项目: gwt-eclipse-plugin   文件: JavaASTUtilsTest.java
@Override
protected void setUp() throws Exception {
  super.setUp();

  // Have JDT parse the compilation unit
  ASTParser parser = ASTParser.newParser(AST.JLS3);
  parser.setProject(getTestProject());
  parser.setSource(testClass.getCompilationUnit());
  ast = parser.createAST(null);
}
 
/**
 * Creates the necessary change to updated a comment reference represented
 * by a search match.
 *
 * @param rewrite
 *            the current compilation unit rewrite
 * @param declaration
 *            the source method declaration
 * @param match
 *            the search match representing the method reference
 * @param status
 *            the refactoring status
 */
protected void createMethodJavadocReference(CompilationUnitRewrite rewrite, MethodDeclaration declaration, SearchMatch match, RefactoringStatus status) {
	Assert.isNotNull(rewrite);
	Assert.isNotNull(declaration);
	Assert.isNotNull(match);
	Assert.isNotNull(status);
	final ASTNode node= ASTNodeSearchUtil.findNode(match, rewrite.getRoot());
	if (node instanceof MethodRef) {
		final AST ast= node.getAST();
		final MethodRef successor= ast.newMethodRef();

		rewrite.getASTRewrite().replace(node, successor, null);
	}
}
 
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;
}
 
private static Statement copyStatementExceptBreak(AST ast, ASTRewrite rewrite, Statement source) {
	if (source instanceof Block) {
		Block block= (Block) source;
		Block newBlock= ast.newBlock();
		for (Iterator<Statement> iter= block.statements().iterator(); iter.hasNext();) {
			Statement statement= iter.next();
			if (statement instanceof BreakStatement) {
				continue;
			}
			newBlock.statements().add(copyStatementExceptBreak(ast, rewrite, statement));
		}
		return newBlock;
	}
	return (Statement) rewrite.createMoveTarget(source);
}
 
public static TagElement createParamTag(String parameterName, AST ast, IJavaProject javaProject) {
	TagElement paramNode= ast.newTagElement();
	paramNode.setTagName(TagElement.TAG_PARAM);

	SimpleName simpleName= ast.newSimpleName(parameterName);
	paramNode.fragments().add(simpleName);

	TextElement textElement= ast.newTextElement();
	String text= StubUtility.getTodoTaskTag(javaProject);
	if (text != null)
		textElement.setText(text); //TODO: use template with {@todo} ...
	paramNode.fragments().add(textElement);

	return paramNode;
}
 
源代码22 项目: eclipse.jdt.ls   文件: CastCorrectionProposal.java
private Type getNewCastTypeNode(ASTRewrite rewrite, ImportRewrite importRewrite) {
	AST ast= rewrite.getAST();

	ImportRewriteContext context= new ContextSensitiveImportRewriteContext((CompilationUnit) fNodeToCast.getRoot(), fNodeToCast.getStartPosition(), importRewrite);

	if (fCastType != null) {
		return importRewrite.addImport(fCastType, ast,context, TypeLocation.CAST);
	}

	ASTNode node= fNodeToCast;
	ASTNode parent= node.getParent();
	if (parent instanceof CastExpression) {
		node= parent;
		parent= parent.getParent();
	}
	while (parent instanceof ParenthesizedExpression) {
		node= parent;
		parent= parent.getParent();
	}
	if (parent instanceof MethodInvocation) {
		MethodInvocation invocation= (MethodInvocation) node.getParent();
		if (invocation.getExpression() == node) {
			IBinding targetContext= ASTResolving.getParentMethodOrTypeBinding(node);
			ITypeBinding[] bindings= ASTResolving.getQualifierGuess(node.getRoot(), invocation.getName().getIdentifier(), invocation.arguments(), targetContext);
			if (bindings.length > 0) {
				ITypeBinding first= getCastFavorite(bindings, fNodeToCast.resolveTypeBinding());

				Type newTypeNode= importRewrite.addImport(first, ast, context, TypeLocation.CAST);
				return newTypeNode;
			}
		}
	}
	Type newCastType= ast.newSimpleType(ast.newSimpleName("Object")); //$NON-NLS-1$
	return newCastType;
}
 
private Type getConstantType() throws JavaModelException {
	if (fConstantTypeCache == null) {
		IExpressionFragment fragment = getSelectedExpression();
		ITypeBinding typeBinding = guessBindingForReference(fragment.getAssociatedExpression());
		AST ast = fCuRewrite.getAST();
		typeBinding = Bindings.normalizeForDeclarationUse(typeBinding, ast);
		ImportRewrite importRewrite = fCuRewrite.getImportRewrite();
		ImportRewriteContext context = new ContextSensitiveImportRewriteContext(fCuRewrite.getRoot(), fSelectionStart, importRewrite);
		fConstantTypeCache = importRewrite.addImport(typeBinding, ast, context, TypeLocation.FIELD);
	}
	return fConstantTypeCache;
}
 
源代码24 项目: SimFix   文件: TryPurifyByException.java
public Set<String> purify(){
	if(_method != null && _method.getBody() != null){
		AST ast = AST.newAST(AST.JLS8);
		_backupBody = (Block) ASTNode.copySubtree(ast, _method.getBody());
		splitMethodCalls();
	}
	return _purifiedTestCases;
}
 
private void addBuildMethod(CompilationUnitModificationDomain modificationDomain, TypeDeclaration addedInterface) {
    AST ast = modificationDomain.getAst();
    TypeDeclaration originalType = modificationDomain.getOriginalType();
    MethodDeclaration buildMethod = buildMethodDeclarationCreatorFragment.createMethod(ast,
            originalType);
    javadocAdder.addJavadocForBuildMethod(ast, buildMethod);
    addedInterface.bodyDeclarations().add(buildMethod);
}
 
/**
 * Creates and adds the necessary argument declarations to the given factory method.<br>
 * An argument is needed for each original constructor argument for which the
 * evaluation of the actual arguments across all calls was not able to be
 * pushed inside the factory method (e.g. arguments with side-effects, references
 * to fields if the factory method is to be static or reside in a factory class,
 * or arguments that varied across the set of constructor calls).<br>
 * <code>fArgTypes</code> identifies such arguments by a <code>null</code> value.
 * @param ast utility object used to create AST nodes
 * @param newMethod the <code>MethodDeclaration</code> for the factory method
 */
private void createFactoryMethodSignature(AST ast, MethodDeclaration newMethod) {
	List<SingleVariableDeclaration> argDecls= newMethod.parameters();

	for(int i=0; i < fArgTypes.length; i++) {
		SingleVariableDeclaration argDecl= ast.newSingleVariableDeclaration();
		Type argType;

		if (i == (fArgTypes.length - 1) && fCtorIsVarArgs) {
			// The trailing varargs arg has an extra array dimension, compared to
			// what we need to pass to setType()...
			argType= typeNodeForTypeBinding(fArgTypes[i].getElementType(),
					fArgTypes[i].getDimensions()-1, ast);
			argDecl.setVarargs(true);
		} else
			argType= typeNodeForTypeBinding(fArgTypes[i], 0, ast);

		argDecl.setName(ast.newSimpleName(fFormalArgNames[i]));
		argDecl.setType(argType);
		argDecls.add(argDecl);
	}

	ITypeBinding[] ctorExcepts= fCtorBinding.getExceptionTypes();
	List<Type> exceptions= newMethod.thrownExceptionTypes();

	for(int i=0; i < ctorExcepts.length; i++) {
		exceptions.add(fImportRewriter.addImport(ctorExcepts[i], ast));
	}

       copyTypeParameters(ast, newMethod);
}
 
@Override
public final boolean visit(final SuperFieldAccess node) {
	if (!fAnonymousClassDeclaration && !fTypeDeclarationStatement) {
		final AST ast= node.getAST();
		final FieldAccess access= ast.newFieldAccess();
		access.setExpression(ast.newThisExpression());
		access.setName(ast.newSimpleName(node.getName().getIdentifier()));
		fRewrite.replace(node, access, null);
		if (!fSourceRewriter.getCu().equals(fTargetRewriter.getCu()))
			fSourceRewriter.getImportRemover().registerRemovedNode(node);
		return true;
	}
	return false;
}
 
源代码28 项目: SparkBuilderGenerator   文件: JavadocAdder.java
public void addJavadocForWithBuilderMethod(AST ast, String typeName, String parameterName, MethodDeclaration builderMethod) {
    if (preferencesManager.getPreferenceValue(PluginPreferenceList.GENERATE_JAVADOC_ON_BUILDER_METHOD)) {
        Javadoc javadoc = javadocGenerator.generateJavadoc(ast,
                String.format(Locale.ENGLISH, "Creates builder to build {@link %s} and setting %s parameter.", typeName, parameterName),
                Collections.singletonMap(RETURN_JAVADOC_TAG_NAME, "created builder"));
        builderMethod.setJavadoc(javadoc);
    }
}
 
private void replaceExpressionsWithConstant() throws JavaModelException {
	ASTRewrite astRewrite= fCuRewrite.getASTRewrite();
	AST ast= astRewrite.getAST();

	IASTFragment[] fragmentsToReplace= getFragmentsToReplace();
	for (int i= 0; i < fragmentsToReplace.length; i++) {
		IASTFragment fragment= fragmentsToReplace[i];
		ASTNode node= fragment.getAssociatedNode();
		boolean inTypeDeclarationAnnotation= isInTypeDeclarationAnnotation(node);
		if (inTypeDeclarationAnnotation && JdtFlags.VISIBILITY_STRING_PRIVATE == getVisibility())
			continue;

		SimpleName ref= ast.newSimpleName(fConstantName);
		Name replacement= ref;
		boolean qualifyReference= qualifyReferencesWithDeclaringClassName();
		if (!qualifyReference) {
			qualifyReference= inTypeDeclarationAnnotation;
		}
		if (qualifyReference) {
			replacement= ast.newQualifiedName(ast.newSimpleName(getContainingTypeBinding().getName()), ref);
		}
		TextEditGroup description= fCuRewrite.createGroupDescription(RefactoringCoreMessages.ExtractConstantRefactoring_replace);

		fragment.replace(astRewrite, replacement, description);
		if (fLinkedProposalModel != null)
			fLinkedProposalModel.getPositionGroup(KEY_NAME, true).addPosition(astRewrite.track(ref), false);
	}
}
 
private static void addExceptionToThrows(AST ast, MethodDeclaration methodDeclaration, ASTRewrite rewrite, Type type2) {
	ITypeBinding binding= type2.resolveBinding();
	if (binding == null || isNotYetThrown(binding, methodDeclaration.thrownExceptionTypes())) {
		Type newType= (Type) ASTNode.copySubtree(ast, type2);

		ListRewrite listRewriter= rewrite.getListRewrite(methodDeclaration, MethodDeclaration.THROWN_EXCEPTION_TYPES_PROPERTY);
		listRewriter.insertLast(newType, null);
	}
}
 
 类所在包
 同包方法