Java Code Examples for org.eclipse.jdt.core.dom.ParameterizedType#typeArguments()

The following examples show how to use org.eclipse.jdt.core.dom.ParameterizedType#typeArguments() . 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: TypeResolver.java    From KodeBeagle with Apache License 2.0 6 votes vote down vote up
/**
 * @param type
 * @return
 */
private String getParametrizedType(final ParameterizedType type, final Boolean innerTypes) {
	final StringBuilder sb = new StringBuilder(getFullyQualifiedNameFor(type
			.getType().toString()));

	if(innerTypes) {
		sb.append("<");
		for (final Object typeArg : type.typeArguments()) {
			final Type arg = (Type) typeArg;
			final String argString = getNameOfType(arg);
			sb.append(argString);
			sb.append(",");
		}
		sb.deleteCharAt(sb.length() - 1);
		sb.append(">");
	}
	return sb.toString();
}
 
Example 2
Source File: UiBinderJavaValidator.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
private static ITypeBinding getOwnerTypeBinding(
    TypeDeclaration uiBinderSubtype) {
  List<Type> superInterfaces = uiBinderSubtype.superInterfaceTypes();
  for (Type superInterface : superInterfaces) {
    ITypeBinding binding = superInterface.resolveBinding();
    if (binding != null) {
      if (binding.getErasure().getQualifiedName().equals(
          UiBinderConstants.UI_BINDER_TYPE_NAME)) {
        if (superInterface instanceof ParameterizedType) {
          ParameterizedType uiBinderType = (ParameterizedType) superInterface;
          List<Type> typeArgs = uiBinderType.typeArguments();
          if (typeArgs.size() == 2) {
            Type ownerType = typeArgs.get(1);
            return ownerType.resolveBinding();
          }
        }
      }
    }
  }
  return null;
}
 
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: 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 5
Source File: Resolver.java    From DesigniteJava with Apache License 2.0 5 votes vote down vote up
private void specifyTypes(Type type) {
	if (type.isParameterizedType()) {
		ParameterizedType parameterizedType = (ParameterizedType) type;
		List<Type> typeArgs = parameterizedType.typeArguments();

		for (int i = 0; i < typeArgs.size(); i++)
			setTypeList(typeArgs.get(i));

	} else if (type.isArrayType()) {
		Type arrayType = ((ArrayType) type).getElementType();
		setArrayType(arrayType);
	}
}
 
Example 6
Source File: JavaApproximateTypeInferencer.java    From api-mining with GNU General Public License v3.0 5 votes vote down vote up
/**
 * @param type
 * @return
 */
private String getParametrizedType(final ParameterizedType type) {
	final StringBuffer sb = new StringBuffer(getFullyQualifiedNameFor(type.getType().toString()));
	sb.append("<");
	for (final Object typeArg : type.typeArguments()) {
		final Type arg = (Type) typeArg;
		final String argString = getNameOfType(arg);
		sb.append(argString);
		sb.append(",");
	}
	sb.deleteCharAt(sb.length() - 1);
	sb.append(">");
	return sb.toString();
}
 
Example 7
Source File: AsynchronousInterfaceValidator.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Validate that the AsyncCallback's parameterization and the sync method's
 * return type are assignment compatible.
 */
@SuppressWarnings("unchecked")
private List<CategorizedProblem> doValidateReturnTypes(
    MethodDeclaration node, SingleVariableDeclaration lastParameter,
    ITypeBinding[] parameterTypes, IMethodBinding dependentMethod) {
  ITypeBinding asyncCallbackParam = parameterTypes[parameterTypes.length - 1];
  if (asyncCallbackParam.isParameterizedType()) {
    ITypeBinding[] typeArguments = asyncCallbackParam.getTypeArguments();
    ITypeBinding syncReturnTypeBinding = dependentMethod.getReturnType();

    ITypeBinding typeBinding = syncReturnTypeBinding;
    if (syncReturnTypeBinding.isPrimitive()) {
      String qualifiedWrapperTypeName = JavaASTUtils.getWrapperTypeName(syncReturnTypeBinding.getQualifiedName());
      typeBinding = node.getAST().resolveWellKnownType(
          qualifiedWrapperTypeName);
    }

    boolean compatible = false;
    if (typeBinding != null) {
      compatible = canAssign(typeArguments[0], typeBinding);
    }

    if (!compatible) {
      ParameterizedType parameterizedType = (ParameterizedType) lastParameter.getType();
      List<Type> types = parameterizedType.typeArguments();
      CategorizedProblem problem = RemoteServiceProblemFactory.newAsyncCallbackTypeArgumentMismatchOnAsync(
          types.get(0), typeArguments[0], syncReturnTypeBinding);
      if (problem != null) {
        return Collections.singletonList(problem);
      }
    }
  }

  return Collections.emptyList();
}
 
Example 8
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 9
Source File: Java50Fix.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public void rewriteAST(CompilationUnitRewrite cuRewrite, LinkedProposalModel positionGroups) throws CoreException {
	InferTypeArgumentsTCModel model= new InferTypeArgumentsTCModel();
	InferTypeArgumentsConstraintCreator creator= new InferTypeArgumentsConstraintCreator(model, true);

	CompilationUnit root= cuRewrite.getRoot();
	root.accept(creator);

	InferTypeArgumentsConstraintsSolver solver= new InferTypeArgumentsConstraintsSolver(model);
	InferTypeArgumentsUpdate update= solver.solveConstraints(new NullProgressMonitor());
	solver= null; //free caches

	ParameterizedType[] nodes= InferTypeArgumentsRefactoring.inferArguments(fTypes, update, model, cuRewrite);
	if (nodes.length == 0)
		return;

	ASTRewrite astRewrite= cuRewrite.getASTRewrite();
	for (int i= 0; i < nodes.length; i++) {
		ParameterizedType type= nodes[i];
		List<Type> args= type.typeArguments();
		int j= 0;
		for (Iterator<Type> iter= args.iterator(); iter.hasNext();) {
			LinkedProposalPositionGroup group= new LinkedProposalPositionGroup("G" + i + "_" + j); //$NON-NLS-1$ //$NON-NLS-2$
			Type argType= iter.next();
			if (!positionGroups.hasLinkedPositions()) {
				group.addPosition(astRewrite.track(argType), true);
			} else {
				group.addPosition(astRewrite.track(argType), false);
			}
			positionGroups.addPositionGroup(group);
			j++;
		}
	}
	positionGroups.setEndPosition(astRewrite.track(nodes[0]));
}
 
Example 10
Source File: BindingSignatureVisitor.java    From JDeodorant with MIT License 5 votes vote down vote up
public boolean visit(ParameterizedType type) {
	handleType(type.getType());
	List typeArguments = type.typeArguments();
	for (int i = 0; i < typeArguments.size(); i++) {
		handleType((Type) typeArguments.get(i));
	}
	return false;
}
 
Example 11
Source File: Util.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Sync method has same return type as parameterization of last async
 * parameter (AsyncCallback). If the async callback parameter type is raw,
 * just assume sync return type of void.
 *
 * @param ast {@link AST} associated with the destination compilation unit
 * @param asyncMethod the GWT RPC async method declaration
 * @param imports {@link ImportRewrite} associated with the destination
 *          compilation unit
 * @return the computed return {@link Type}
 */
public static Type computeSyncReturnType(AST ast,
    MethodDeclaration asyncMethod, ImportRewrite imports) {
  Type returnType = ast.newPrimitiveType(PrimitiveType.VOID);
  @SuppressWarnings("unchecked")
  List<SingleVariableDeclaration> asyncParameters = asyncMethod.parameters();

  // Check for no parameters on async method... just in case
  if (asyncParameters.isEmpty()) {
    return returnType;
  }

  // Grab the last parameter type, which should be the callback
  Type callbackType = asyncParameters.get(asyncParameters.size() - 1).getType();

  // Make sure we have a parameterized callback type; otherwise, we can't
  // infer the return type of the sync method.
  if (callbackType.isParameterizedType()) {
    ParameterizedType callbackParamType = (ParameterizedType) callbackType;

    ITypeBinding callbackBinding = callbackParamType.getType().resolveBinding();
    if (callbackBinding == null) {
      return returnType;
    }

    // Make sure the callback is of type AsyncCallback
    String callbackBaseTypeName = callbackBinding.getErasure().getQualifiedName();
    if (callbackBaseTypeName.equals(RemoteServiceUtilities.ASYNCCALLBACK_QUALIFIED_NAME)) {
      @SuppressWarnings("unchecked")
      List<Type> callbackTypeArgs = callbackParamType.typeArguments();

      // Make sure we only have one type argument
      if (callbackTypeArgs.size() == 1) {
        Type callbackTypeParameter = callbackTypeArgs.get(0);

        // Check for primitive wrapper type; if we have one use the actual
        // primitive for the sync return type.
        // TODO(): Maybe used linked mode to let the user choose whether to
        // return the primitive or its wrapper type.
        String qualifiedName = callbackTypeParameter.resolveBinding().getQualifiedName();
        String primitiveTypeName = JavaASTUtils.getPrimitiveTypeName(qualifiedName);
        if (primitiveTypeName != null) {
          return ast.newPrimitiveType(PrimitiveType.toCode(primitiveTypeName));
        }

        returnType = JavaASTUtils.normalizeTypeAndAddImport(ast,
            callbackTypeParameter, imports);
      }
    }
  }

  return returnType;
}
 
Example 12
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"));
}