Java Code Examples for org.eclipse.jdt.core.dom.AST#newParameterizedType()

The following examples show how to use org.eclipse.jdt.core.dom.AST#newParameterizedType() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: CreateDoPrivilegedBlockResolution.java    From spotbugs with GNU Lesser General Public License v2.1 6 votes vote down vote up
private ParameterizedType createPrivilegedActionType(ASTRewrite rewrite, ClassInstanceCreation classLoaderCreation) {
    AST ast = rewrite.getAST();

    Name privilegedActionName;
    if (isUpdateImports()) {
        privilegedActionName = ast.newSimpleName(PrivilegedAction.class.getSimpleName());
    } else {
        privilegedActionName = ast.newName(PrivilegedAction.class.getName());
    }
    SimpleType rawPrivilegedActionType = ast.newSimpleType(privilegedActionName);
    ParameterizedType privilegedActionType = ast.newParameterizedType(rawPrivilegedActionType);
    Type typeArgument = (Type) rewrite.createCopyTarget(classLoaderCreation.getType());
    List<Type> typeArguments = checkedList(privilegedActionType.typeArguments());

    typeArguments.add(typeArgument);

    return privilegedActionType;
}
 
Example 2
Source File: IntroduceFactoryRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Sets the return type of the factory method, including any necessary type
 * arguments. E.g., for constructor <code>Foo()</code> in <code>Foo&lt;T&gt;</code>,
 * the factory method defines a method type parameter <code>&lt;T&gt;</code> and
 * returns a <code>Foo&lt;T&gt;</code>.
 * @param newMethod the method whose return type is to be set
 * @param retTypeName the simple name of the return type (without type parameters)
 * @param ctorOwnerTypeParameters the formal type parameters of the type that the
 * factory method instantiates (whose constructor is being encapsulated)
 * @param ast utility object used to create AST nodes
 */
private void setMethodReturnType(MethodDeclaration newMethod, String retTypeName, ITypeBinding[] ctorOwnerTypeParameters, AST ast) {
       if (ctorOwnerTypeParameters.length == 0)
           newMethod.setReturnType2(ast.newSimpleType(ast.newSimpleName(retTypeName)));
       else {
           Type baseType= ast.newSimpleType(ast.newSimpleName(retTypeName));
           ParameterizedType newRetType= ast.newParameterizedType(baseType);
           List<Type> newRetTypeArgs= newRetType.typeArguments();

           for(int i= 0; i < ctorOwnerTypeParameters.length; i++) {
               Type retTypeArg= ASTNodeFactory.newType(ast, ctorOwnerTypeParameters[i].getName());

               newRetTypeArgs.add(retTypeArg);
           }
           newMethod.setReturnType2(newRetType);
       }
}
 
Example 3
Source File: IntroduceFactoryRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Sets the type being instantiated in the given constructor call, including
    * specifying any necessary type arguments.
 * @param newCtorCall the constructor call to modify
 * @param ctorTypeName the simple name of the type being instantiated
 * @param ctorOwnerTypeParameters the formal type parameters of the type being
 * instantiated
 * @param ast utility object used to create AST nodes
 */
private void setCtorTypeArguments(ClassInstanceCreation newCtorCall, String ctorTypeName, ITypeBinding[] ctorOwnerTypeParameters, AST ast) {
       if (ctorOwnerTypeParameters.length == 0) // easy, just a simple type
           newCtorCall.setType(ASTNodeFactory.newType(ast, ctorTypeName));
       else {
           Type baseType= ast.newSimpleType(ast.newSimpleName(ctorTypeName));
           ParameterizedType newInstantiatedType= ast.newParameterizedType(baseType);
           List<Type> newInstTypeArgs= newInstantiatedType.typeArguments();

           for(int i= 0; i < ctorOwnerTypeParameters.length; i++) {
               Type typeArg= ASTNodeFactory.newType(ast, ctorOwnerTypeParameters[i].getName());

               newInstTypeArgs.add(typeArg);
           }
           newCtorCall.setType(newInstantiatedType);
       }
}
 
Example 4
Source File: ConvertAnonymousToNestedRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private ASTNode createNewClassInstanceCreation(CompilationUnitRewrite rewrite, ITypeBinding[] parameters) {
	AST ast= fAnonymousInnerClassNode.getAST();
	ClassInstanceCreation newClassCreation= ast.newClassInstanceCreation();
	newClassCreation.setAnonymousClassDeclaration(null);
	Type type= null;
	SimpleName newNameNode= ast.newSimpleName(fClassName);
	if (parameters.length > 0) {
		final ParameterizedType parameterized= ast.newParameterizedType(ast.newSimpleType(newNameNode));
		for (int index= 0; index < parameters.length; index++)
			parameterized.typeArguments().add(ast.newSimpleType(ast.newSimpleName(parameters[index].getName())));
		type= parameterized;
	} else
		type= ast.newSimpleType(newNameNode);
	newClassCreation.setType(type);
	copyArguments(rewrite, newClassCreation);
	addArgumentsForLocalsUsedInInnerClass(newClassCreation);

	addLinkedPosition(KEY_TYPE_NAME, newNameNode, rewrite.getASTRewrite(), true);

	return newClassCreation;
}
 
Example 5
Source File: ChangeTypeRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Creates the appropriate ParameterizedType node. Recursion is needed to
 * handle the nested case (e.g., Vector<Vector<String>>).
 * @param ast
 * @param typeBinding
 * @return the created type
 */
private Type createParameterizedType(AST ast, ITypeBinding typeBinding){
	if (typeBinding.isParameterizedType() && !typeBinding.isRawType()){
		Type baseType= ast.newSimpleType(ASTNodeFactory.newName(ast, typeBinding.getErasure().getName()));
		ParameterizedType newType= ast.newParameterizedType(baseType);
		for (int i=0; i < typeBinding.getTypeArguments().length; i++){
			ITypeBinding typeArg= typeBinding.getTypeArguments()[i];
			Type argType= createParameterizedType(ast, typeArg); // recursive call
			newType.typeArguments().add(argType);
		}
		return newType;
	} else {
		if (!typeBinding.isTypeVariable()){
			return ast.newSimpleType(ASTNodeFactory.newName(ast, typeBinding.getErasure().getName()));
		} else {
			return ast.newSimpleType(ast.newSimpleName(typeBinding.getName()));
		}
	}
}
 
Example 6
Source File: MoveInnerToTopRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private ASTNode getNewQualifiedNameNode(ITypeBinding[] parameters, Name name) {
	final AST ast= name.getAST();
	boolean raw= false;
	final ITypeBinding binding= name.resolveTypeBinding();
	if (binding != null && binding.isRawType())
		raw= true;
	if (parameters != null && parameters.length > 0 && !raw) {
		final ParameterizedType type= ast.newParameterizedType(ast.newSimpleType(ast.newName(fQualifiedTypeName)));
		for (int index= 0; index < parameters.length; index++)
			type.typeArguments().add(ast.newSimpleType(ast.newSimpleName(parameters[index].getName())));
		return type;
	}
	return ast.newName(fQualifiedTypeName);
}
 
Example 7
Source File: MoveInnerToTopRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private ASTNode getNewUnqualifiedTypeNode(ITypeBinding[] parameters, Name name) {
	final AST ast= name.getAST();
	boolean raw= false;
	final ITypeBinding binding= name.resolveTypeBinding();
	if (binding != null && binding.isRawType())
		raw= true;
	if (parameters != null && parameters.length > 0 && !raw) {
		final ParameterizedType type= ast.newParameterizedType(ast.newSimpleType(ast.newSimpleName(fType.getElementName())));
		for (int index= 0; index < parameters.length; index++)
			type.typeArguments().add(ast.newSimpleType(ast.newSimpleName(parameters[index].getName())));
		return type;
	}
	return ast.newSimpleType(ast.newSimpleName(fType.getElementName()));
}
 
Example 8
Source File: ExtractInterfaceProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Creates the new signature of the source type.
 *
 * @param rewrite
 *            the source compilation unit rewrite
 * @param declaration
 *            the type declaration
 * @param status
 *            the refactoring status
 * @param monitor
 *            the progress monitor to use
 * @throws JavaModelException
 *             if the type parameters cannot be retrieved
 */
protected final void createTypeSignature(final CompilationUnitRewrite rewrite, final AbstractTypeDeclaration declaration, final RefactoringStatus status, final IProgressMonitor monitor) throws JavaModelException {
	Assert.isNotNull(rewrite);
	Assert.isNotNull(declaration);
	Assert.isNotNull(status);
	Assert.isNotNull(monitor);
	try {
		monitor.beginTask("", 1); //$NON-NLS-1$
		monitor.setTaskName(RefactoringCoreMessages.ExtractInterfaceProcessor_creating);
		final AST ast= declaration.getAST();
		final ITypeParameter[] parameters= fSubType.getTypeParameters();
		Type type= ast.newSimpleType(ast.newSimpleName(fSuperName));
		if (parameters.length > 0) {
			final ParameterizedType parameterized= ast.newParameterizedType(type);
			for (int index= 0; index < parameters.length; index++)
				parameterized.typeArguments().add(ast.newSimpleType(ast.newSimpleName(parameters[index].getElementName())));
			type= parameterized;
		}
		final ASTRewrite rewriter= rewrite.getASTRewrite();
		if (declaration instanceof TypeDeclaration)
			rewriter.getListRewrite(declaration, TypeDeclaration.SUPER_INTERFACE_TYPES_PROPERTY).insertLast(type, rewrite.createCategorizedGroupDescription(RefactoringCoreMessages.ExtractInterfaceProcessor_add_super_interface, SET_EXTRACT_INTERFACE));
		else if (declaration instanceof EnumDeclaration)
			rewriter.getListRewrite(declaration, EnumDeclaration.SUPER_INTERFACE_TYPES_PROPERTY).insertLast(type, rewrite.createCategorizedGroupDescription(RefactoringCoreMessages.ExtractInterfaceProcessor_add_super_interface, SET_EXTRACT_INTERFACE));
		monitor.worked(1);
	} finally {
		monitor.done();
	}
}
 
Example 9
Source File: MoveInnerToTopRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private Type createEnclosingType(final AST ast) throws JavaModelException {
	Assert.isNotNull(ast);
	final ITypeParameter[] parameters= fType.getDeclaringType().getTypeParameters();
	final Type type= ASTNodeFactory.newType(ast, fType.getDeclaringType().getTypeQualifiedName('.'));
	if (parameters.length > 0) {
		final ParameterizedType parameterized= ast.newParameterizedType(type);
		for (int index= 0; index < parameters.length; index++)
			parameterized.typeArguments().add(ast.newSimpleType(ast.newSimpleName(parameters[index].getElementName())));
		return parameterized;
	}
	return type;
}
 
Example 10
Source File: ExtractSupertypeProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Creates a new type signature of a subtype.
 *
 * @param subRewrite
 *            the compilation unit rewrite of a subtype
 * @param declaration
 *            the type declaration of a subtype
 * @param extractedType
 *            the extracted super type
 * @param extractedBinding
 *            the binding of the extracted super type
 * @param monitor
 *            the progress monitor to use
 * @throws JavaModelException
 *             if the type parameters cannot be retrieved
 */
protected final void createTypeSignature(final CompilationUnitRewrite subRewrite, final AbstractTypeDeclaration declaration, final IType extractedType, final ITypeBinding extractedBinding, final IProgressMonitor monitor) throws JavaModelException {
	Assert.isNotNull(subRewrite);
	Assert.isNotNull(declaration);
	Assert.isNotNull(extractedType);
	Assert.isNotNull(monitor);
	try {
		monitor.beginTask(RefactoringCoreMessages.ExtractSupertypeProcessor_preparing, 10);
		final AST ast= subRewrite.getAST();
		Type type= null;
		if (extractedBinding != null) {
			type= subRewrite.getImportRewrite().addImport(extractedBinding, ast);
		} else {
			subRewrite.getImportRewrite().addImport(extractedType.getFullyQualifiedName('.'));
			type= ast.newSimpleType(ast.newSimpleName(extractedType.getElementName()));
		}
		subRewrite.getImportRemover().registerAddedImport(extractedType.getFullyQualifiedName('.'));
		if (type != null) {
			final ITypeParameter[] parameters= extractedType.getTypeParameters();
			if (parameters.length > 0) {
				final ParameterizedType parameterized= ast.newParameterizedType(type);
				for (int index= 0; index < parameters.length; index++)
					parameterized.typeArguments().add(ast.newSimpleType(ast.newSimpleName(parameters[index].getElementName())));
				type= parameterized;
			}
		}
		final ASTRewrite rewriter= subRewrite.getASTRewrite();
		if (type != null && declaration instanceof TypeDeclaration) {
			final TypeDeclaration extended= (TypeDeclaration) declaration;
			final Type superClass= extended.getSuperclassType();
			if (superClass != null) {
				rewriter.replace(superClass, type, subRewrite.createCategorizedGroupDescription(RefactoringCoreMessages.ExtractSupertypeProcessor_add_supertype, SET_EXTRACT_SUPERTYPE));
				subRewrite.getImportRemover().registerRemovedNode(superClass);
			} else
				rewriter.set(extended, TypeDeclaration.SUPERCLASS_TYPE_PROPERTY, type, subRewrite.createCategorizedGroupDescription(RefactoringCoreMessages.ExtractSupertypeProcessor_add_supertype, SET_EXTRACT_SUPERTYPE));
		}
	} finally {
		monitor.done();
	}
}
 
Example 11
Source File: Util.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Creates a GWT RPC async callback parameter declaration based on the sync
 * method return type.
 *
 * @param ast {@link AST} associated with the destination compilation unit
 * @param syncReturnType the sync method return type
 * @param callbackParameterName name of the callback parameter
 * @param imports {@link ImportsRewrite} for the destination compilation unit
 * @return callback paramter declaration
 */
@SuppressWarnings("unchecked")
public static SingleVariableDeclaration createAsyncCallbackParameter(AST ast,
    Type syncReturnType, String callbackParameterName, ImportRewrite imports) {
  ITypeBinding syncReturnTypeBinding = syncReturnType.resolveBinding();

  SingleVariableDeclaration parameter = ast.newSingleVariableDeclaration();

  String gwtCallbackTypeSig = Signature.createTypeSignature(
      RemoteServiceUtilities.ASYNCCALLBACK_QUALIFIED_NAME, true);
  Type gwtCallbackType = imports.addImportFromSignature(gwtCallbackTypeSig,
      ast);

  if (syncReturnTypeBinding.isPrimitive()) {
    String wrapperName = JavaASTUtils.getWrapperTypeName(syncReturnTypeBinding.getName());
    String wrapperTypeSig = Signature.createTypeSignature(wrapperName, true);
    syncReturnType = imports.addImportFromSignature(wrapperTypeSig, ast);
  } else {
    syncReturnType = JavaASTUtils.normalizeTypeAndAddImport(ast,
        syncReturnType, imports);
  }

  ParameterizedType type = ast.newParameterizedType(gwtCallbackType);
  List<Type> typeArgs = type.typeArguments();
  typeArgs.add(syncReturnType);

  parameter.setType(type);
  parameter.setName(ast.newSimpleName(callbackParameterName));

  return parameter;
}
 
Example 12
Source File: ReferencedClassesParserTest.java    From BUILD_file_generator with Apache License 2.0 5 votes vote down vote up
@Test
public void testExtractTypeNameWithoutGenerics() {
  AST ast = AST.newAST(AST.JLS4);
  org.eclipse.jdt.core.dom.SimpleName entry = ast.newSimpleName("Entry");
  ParameterizedType map = ast.newParameterizedType(ast.newSimpleType(ast.newSimpleName("Map")));
  map.typeArguments().add(ast.newSimpleType(ast.newSimpleName("Foo")));
  QualifiedType type = ast.newQualifiedType(map, entry);
  assertThat(type.toString()).isEqualTo("Map<Foo>.Entry");
  assertThat(ReferencedClassesParser.extractTypeNameWithoutGenerics(type)).isEqualTo("Map.Entry");
}
 
Example 13
Source File: ASTNodeFactory.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public static Type newCreationType(AST ast, ITypeBinding typeBinding, ImportRewrite importRewrite, ImportRewriteContext importContext) {
	if (typeBinding.isParameterizedType()) {
		Type baseType= newCreationType(ast, typeBinding.getTypeDeclaration(), importRewrite, importContext);
		ParameterizedType parameterizedType= ast.newParameterizedType(baseType);
		for (ITypeBinding typeArgument : typeBinding.getTypeArguments()) {
			parameterizedType.typeArguments().add(newCreationType(ast, typeArgument, importRewrite, importContext));
		}
		return parameterizedType;
		
	} else if (typeBinding.isParameterizedType()) {
		Type elementType= newCreationType(ast, typeBinding.getElementType(), importRewrite, importContext);
		ArrayType arrayType= ast.newArrayType(elementType, 0);
		while (typeBinding.isArray()) {
			Dimension dimension= ast.newDimension();
			IAnnotationBinding[] typeAnnotations= typeBinding.getTypeAnnotations();
			for (IAnnotationBinding typeAnnotation : typeAnnotations) {
				dimension.annotations().add(importRewrite.addAnnotation(typeAnnotation, ast, importContext));
			}
			arrayType.dimensions().add(dimension);
			typeBinding= typeBinding.getComponentType();
		}
		return arrayType;
			
	} else if (typeBinding.isWildcardType()) {
		ITypeBinding bound= typeBinding.getBound();
		typeBinding= (bound != null) ? bound : typeBinding.getErasure();
		return newCreationType(ast, typeBinding, importRewrite, importContext);
		
	} else {
		return importRewrite.addImport(typeBinding, ast, importContext);
	}
}
 
Example 14
Source File: ExtractToNullCheckedLocalProposal.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/** 
 * Create a fresh type reference
 * @param typeBinding the type we want to refer to
 * @param ast AST for creating new nodes
 * @param imports use this for optimal type names
 * @return a fully features non-null type reference (can be parameterized and/or array).
 */
public static Type newType(ITypeBinding typeBinding, AST ast, ImportRewrite imports) {
	// unwrap array type:
	int dimensions= typeBinding.getDimensions();
	if (dimensions > 0)
		typeBinding= typeBinding.getElementType();
	
	// unwrap parameterized type:
	ITypeBinding[] typeArguments= typeBinding.getTypeArguments();
	typeBinding= typeBinding.getErasure();	

	// create leaf type:
	Type elementType = (typeBinding.isPrimitive())
				? ast.newPrimitiveType(PrimitiveType.toCode(typeBinding.getName()))
				: ast.newSimpleType(ast.newName(imports.addImport(typeBinding)));

	// re-wrap as parameterized type:
	if (typeArguments.length > 0) {
		ParameterizedType parameterizedType= ast.newParameterizedType(elementType);
		for (ITypeBinding typeArgument : typeArguments)
			parameterizedType.typeArguments().add(newType(typeArgument, ast, imports));
		elementType = parameterizedType;
	}
	
	// re-wrap as array type:
	if (dimensions > 0)
		return ast.newArrayType(elementType, dimensions);
	else
		return elementType;
}
 
Example 15
Source File: RefactoringUtility.java    From JDeodorant with MIT License 5 votes vote down vote up
private static ParameterizedType createQualifiedParameterizedType(AST ast, ITypeBinding typeBinding, ASTRewrite rewriter) {
	ITypeBinding erasure = typeBinding.getErasure();
	ITypeBinding[] typeArguments = typeBinding.getTypeArguments();
	ParameterizedType parameterizedType = ast.newParameterizedType(generateQualifiedTypeFromTypeBinding(erasure, ast, rewriter));
	ListRewrite typeArgumentsRewrite = rewriter.getListRewrite(parameterizedType, ParameterizedType.TYPE_ARGUMENTS_PROPERTY);
	for(ITypeBinding typeArgument : typeArguments) {
		typeArgumentsRewrite.insertLast(generateQualifiedTypeFromTypeBinding(typeArgument, ast, rewriter), null);
	}
	return parameterizedType;
}
 
Example 16
Source File: RefactoringUtility.java    From JDeodorant with MIT License 5 votes vote down vote up
private static ParameterizedType createParameterizedType(AST ast, ITypeBinding typeBinding, ASTRewrite rewriter) {
	ITypeBinding erasure = typeBinding.getErasure();
	ITypeBinding[] typeArguments = typeBinding.getTypeArguments();
	ParameterizedType parameterizedType = ast.newParameterizedType(generateTypeFromTypeBinding(erasure, ast, rewriter));
	ListRewrite typeArgumentsRewrite = rewriter.getListRewrite(parameterizedType, ParameterizedType.TYPE_ARGUMENTS_PROPERTY);
	for(ITypeBinding typeArgument : typeArguments) {
		typeArgumentsRewrite.insertLast(generateTypeFromTypeBinding(typeArgument, ast, rewriter), null);
	}
	return parameterizedType;
}
 
Example 17
Source File: JavaStatementPostfixContext.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
private Type createType(String typeSig, AST ast) {
	int sigKind = Signature.getTypeSignatureKind(typeSig);
       switch (sigKind) {
           case Signature.BASE_TYPE_SIGNATURE:
               return ast.newPrimitiveType(PrimitiveType.toCode(Signature.toString(typeSig)));
           case Signature.ARRAY_TYPE_SIGNATURE:
               Type elementType = createType(Signature.getElementType(typeSig), ast);
               return ast.newArrayType(elementType, Signature.getArrayCount(typeSig));
           case Signature.CLASS_TYPE_SIGNATURE:
               String erasureSig = Signature.getTypeErasure(typeSig);

               String erasureName = Signature.toString(erasureSig);
               if (erasureSig.charAt(0) == Signature.C_RESOLVED) {
                   erasureName = addImport(erasureName);
               }
               
               Type baseType= ast.newSimpleType(ast.newName(erasureName));
               String[] typeArguments = Signature.getTypeArguments(typeSig);
               if (typeArguments.length > 0) {
                   ParameterizedType type = ast.newParameterizedType(baseType);
                   List argNodes = type.typeArguments();
                   for (int i = 0; i < typeArguments.length; i++) {
                       String curr = typeArguments[i];
                       if (containsNestedCapture(curr)) {
                           argNodes.add(ast.newWildcardType());
                       } else {
                           argNodes.add(createType(curr, ast));
                       }
                   }
                   return type;
               }
               return baseType;
           case Signature.TYPE_VARIABLE_SIGNATURE:
               return ast.newSimpleType(ast.newSimpleName(Signature.toString(typeSig)));
           case Signature.WILDCARD_TYPE_SIGNATURE:
               WildcardType wildcardType= ast.newWildcardType();
               char ch = typeSig.charAt(0);
               if (ch != Signature.C_STAR) {
                   Type bound= createType(typeSig.substring(1), ast);
                   wildcardType.setBound(bound, ch == Signature.C_EXTENDS);
               }
               return wildcardType;
           case Signature.CAPTURE_TYPE_SIGNATURE:
               return createType(typeSig.substring(1), ast);
       }
       
       return ast.newSimpleType(ast.newName("java.lang.Object"));
}