Java Code Examples for org.eclipse.jdt.core.dom.ITypeBinding#getName()

The following examples show how to use org.eclipse.jdt.core.dom.ITypeBinding#getName() . 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: ReferenceResolvingVisitor.java    From windup with Eclipse Public License 1.0 6 votes vote down vote up
private String getQualifiedName(ITypeBinding typeBinding)
{
    if (typeBinding == null)
        return null;

    String qualifiedName = typeBinding.getQualifiedName();

    if (StringUtils.isEmpty(qualifiedName))
    {
        if (typeBinding.isAnonymous())
        {
            if (typeBinding.getSuperclass() != null)
                qualifiedName = getQualifiedName(typeBinding.getSuperclass());
            else if (typeBinding instanceof AnonymousClassDeclaration)
            {
                qualifiedName = ((AnonymousClassDeclaration) typeBinding).toString();
            }
        }
        else if (StringUtils.isEmpty(qualifiedName) && typeBinding.isNested())
            qualifiedName = typeBinding.getName();
    }

    return qualifiedName;
}
 
Example 2
Source File: JavaTypeHierarchyExtractor.java    From api-mining with GNU General Public License v3.0 6 votes vote down vote up
private void getTypeBindingParents(ITypeBinding binding) {
	if (binding.isParameterizedType()) {
		binding = binding.getErasure();
	}
	final String bindingName = binding.isRecovered() ? binding
			.getName() : binding.getQualifiedName();
	final ITypeBinding superclassBinding = binding.getSuperclass();
	if (superclassBinding != null) {
		addTypes(
				superclassBinding.isRecovered() ? superclassBinding.getName()
						: superclassBinding.getQualifiedName(),
				bindingName);
		getTypeBindingParents(superclassBinding);
	}

	for (ITypeBinding iface : binding.getInterfaces()) {
		if (iface.isParameterizedType()) {
			iface = iface.getErasure();
		}
		addTypes(
				iface.isRecovered() ? iface.getName()
						: iface.getQualifiedName(), bindingName);
		getTypeBindingParents(iface);
	}
}
 
Example 3
Source File: JavaTypeHierarchyExtractor.java    From codemining-core with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private void getTypeBindingParents(ITypeBinding binding) {
	if (binding.isParameterizedType()) {
		binding = binding.getErasure();
	}
	final String bindingName = binding.isRecovered() ? binding
			.getName() : binding.getQualifiedName();
	final ITypeBinding superclassBinding = binding.getSuperclass();
	if (superclassBinding != null) {
		addTypes(
				superclassBinding.isRecovered() ? superclassBinding.getName()
						: superclassBinding.getQualifiedName(),
				bindingName);
		getTypeBindingParents(superclassBinding);
	}

	for (ITypeBinding iface : binding.getInterfaces()) {
		if (iface.isParameterizedType()) {
			iface = iface.getErasure();
		}
		addTypes(
				iface.isRecovered() ? iface.getName()
						: iface.getQualifiedName(), bindingName);
		getTypeBindingParents(iface);
	}
}
 
Example 4
Source File: MissingAnnotationAttributesProposal.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private Expression newDefaultExpression(AST ast, ITypeBinding type, ImportRewriteContext context) {
	if (type.isPrimitive()) {
		String name= type.getName();
		if ("boolean".equals(name)) { //$NON-NLS-1$
			return ast.newBooleanLiteral(false);
		} else {
			return ast.newNumberLiteral("0"); //$NON-NLS-1$
		}
	}
	if (type == ast.resolveWellKnownType("java.lang.String")) { //$NON-NLS-1$
		return ast.newStringLiteral();
	}
	if (type.isArray()) {
		ArrayInitializer initializer= ast.newArrayInitializer();
		initializer.expressions().add(newDefaultExpression(ast, type.getElementType(), context));
		return initializer;
	}
	if (type.isAnnotation()) {
		MarkerAnnotation annotation= ast.newMarkerAnnotation();
		annotation.setTypeName(ast.newName(getImportRewrite().addImport(type, context)));
		return annotation;
	}
	return ast.newNullLiteral();
}
 
Example 5
Source File: StringFormatGenerator.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
@Override
protected Expression createMemberAccessExpression(Object member, boolean ignoreArraysCollections, boolean ignoreNulls) {
	ITypeBinding type= getMemberType(member);
	if (!getContext().is50orHigher() && type.isPrimitive()) {
		String nonPrimitiveType= null;
		String typeName= type.getName();
		if (typeName.equals("byte"))nonPrimitiveType= "java.lang.Byte"; //$NON-NLS-1$ //$NON-NLS-2$
		if (typeName.equals("short"))nonPrimitiveType= "java.lang.Short"; //$NON-NLS-1$ //$NON-NLS-2$
		if (typeName.equals("char"))nonPrimitiveType= "java.lang.Character"; //$NON-NLS-1$ //$NON-NLS-2$
		if (typeName.equals("int"))nonPrimitiveType= "java.lang.Integer"; //$NON-NLS-1$ //$NON-NLS-2$
		if (typeName.equals("long"))nonPrimitiveType= "java.lang.Long"; //$NON-NLS-1$ //$NON-NLS-2$
		if (typeName.equals("float"))nonPrimitiveType= "java.lang.Float"; //$NON-NLS-1$ //$NON-NLS-2$
		if (typeName.equals("double"))nonPrimitiveType= "java.lang.Double"; //$NON-NLS-1$ //$NON-NLS-2$
		if (typeName.equals("boolean"))nonPrimitiveType= "java.lang.Boolean"; //$NON-NLS-1$ //$NON-NLS-2$
		ClassInstanceCreation classInstance= fAst.newClassInstanceCreation();
		classInstance.setType(fAst.newSimpleType(addImport(nonPrimitiveType)));
		classInstance.arguments().add(super.createMemberAccessExpression(member, true, true));
		return classInstance;
	}
	return super.createMemberAccessExpression(member, ignoreArraysCollections, ignoreNulls);
}
 
Example 6
Source File: JavaTypeHierarchyExtractor.java    From tassal with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private void getTypeBindingParents(ITypeBinding binding) {
	if (binding.isParameterizedType()) {
		binding = binding.getErasure();
	}
	final String bindingName = binding.isRecovered() ? binding
			.getName() : binding.getQualifiedName();
	final ITypeBinding superclassBinding = binding.getSuperclass();
	if (superclassBinding != null) {
		addTypes(
				superclassBinding.isRecovered() ? superclassBinding.getName()
						: superclassBinding.getQualifiedName(),
				bindingName);
		getTypeBindingParents(superclassBinding);
	}

	for (ITypeBinding iface : binding.getInterfaces()) {
		if (iface.isParameterizedType()) {
			iface = iface.getErasure();
		}
		addTypes(
				iface.isRecovered() ? iface.getName()
						: iface.getQualifiedName(), bindingName);
		getTypeBindingParents(iface);
	}
}
 
Example 7
Source File: IntroduceParameterRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private List<String> guessTempNamesFromExpression(Expression selectedExpression, String[] excluded) {
	ITypeBinding expressionBinding= Bindings.normalizeForDeclarationUse(
		selectedExpression.resolveTypeBinding(),
		selectedExpression.getAST());
	String typeName= getQualifiedName(expressionBinding);
	if (typeName.length() == 0)
		typeName= expressionBinding.getName();
	if (typeName.length() == 0)
		return Collections.emptyList();
	int typeParamStart= typeName.indexOf("<"); //$NON-NLS-1$
	if (typeParamStart != -1)
		typeName= typeName.substring(0, typeParamStart);
	String[] proposals= StubUtility.getLocalNameSuggestions(fSourceCU.getJavaProject(), typeName, expressionBinding.getDimensions(), excluded);
	return Arrays.asList(proposals);
}
 
Example 8
Source File: InfixExpressionWriter.java    From juniversal with MIT License 5 votes vote down vote up
private void writeRightShiftUnsigned(InfixExpression infixExpression) {
    ITypeBinding typeBinding = infixExpression.getLeftOperand().resolveTypeBinding();
    String typeName = typeBinding.getName();

    //TODO: Remove inner parens for left operand if it's a simple (single elmt) expression, not needing them
    String cSharpTypeName;
    String cSharpUnsignedTypeName;
    if (typeBinding.getName().equals("long")) {
        cSharpTypeName = "long";
        cSharpUnsignedTypeName = "ulong";
    } else if (typeBinding.getName().equals("int")) {
        cSharpTypeName = "int";
        cSharpUnsignedTypeName = "uint";
    } else if (typeBinding.getName().equals("short")) {
        cSharpTypeName = "short";
        cSharpUnsignedTypeName = "ushort";
    } else if (typeBinding.getName().equals("byte")) {
        cSharpTypeName = "sbyte";
        cSharpUnsignedTypeName = "byte";
    }
    else throw new JUniversalException("Unexpected >>> left operand type: " + typeName);

    write("(" + cSharpTypeName + ")((" + cSharpUnsignedTypeName + ")(");
    writeNode(infixExpression.getLeftOperand());
    write(")");

    copySpaceAndComments();
    matchAndWrite(">>>", ">>");
    copySpaceAndComments();

    writeNode(infixExpression.getRightOperand());
    write(")");

    if (infixExpression.hasExtendedOperands())
        throw sourceNotSupported(">>> extended operands (with multiple >>> operators in a row, like 'a >>> b >>> c') not currently supported");
}
 
Example 9
Source File: StubUtility.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public static String[] getVariableNameSuggestions(int variableKind, IJavaProject project, ITypeBinding expectedType, Expression assignedExpression, Collection<String> excluded) {
	LinkedHashSet<String> res= new LinkedHashSet<String>(); // avoid duplicates but keep order

	if (assignedExpression != null) {
		String nameFromExpression= getBaseNameFromExpression(project, assignedExpression, variableKind);
		if (nameFromExpression != null) {
			add(getVariableNameSuggestions(variableKind, project, nameFromExpression, 0, excluded, false), res); // pass 0 as dimension, base name already contains plural.
		}

		String nameFromParent= getBaseNameFromLocationInParent(assignedExpression);
		if (nameFromParent != null) {
			add(getVariableNameSuggestions(variableKind, project, nameFromParent, 0, excluded, false), res); // pass 0 as dimension, base name already contains plural.
		}
	}
	if (expectedType != null) {
		expectedType= Bindings.normalizeTypeBinding(expectedType);
		if (expectedType != null) {
			int dim= 0;
			if (expectedType.isArray()) {
				dim= expectedType.getDimensions();
				expectedType= expectedType.getElementType();
			}
			if (expectedType.isParameterizedType()) {
				expectedType= expectedType.getTypeDeclaration();
			}
			String typeName= expectedType.getName();
			if (typeName.length() > 0) {
				add(getVariableNameSuggestions(variableKind, project, typeName, dim, excluded, false), res);
			}
		}
	}
	if (res.isEmpty()) {
		return getDefaultVariableNameSuggestions(variableKind, excluded);
	}
	return res.toArray(new String[res.size()]);
}
 
Example 10
Source File: ASTNodeFactory.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Returns an expression that is assignable to the given type binding. <code>null</code> is
 * returned if the type is the 'void' type.
 *
 * @param ast The AST to create the expression for
 * @param type The type binding to which the returned expression is compatible to
 * @return the Null-literal for reference types, a boolean-literal for a boolean type, a number
 * literal for primitive types or <code>null</code> if the type is void.
 */
public static Expression newDefaultExpression(AST ast, ITypeBinding type) {
	if (type.isPrimitive()) {
		String name= type.getName();
		if ("boolean".equals(name)) { //$NON-NLS-1$
			return ast.newBooleanLiteral(false);
		} else if ("void".equals(name)) { //$NON-NLS-1$
			return null;
		} else {
			return ast.newNumberLiteral("0"); //$NON-NLS-1$
		}
	}
	return ast.newNullLiteral();
}
 
Example 11
Source File: NecessaryParenthesesChecker.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private static boolean isIntegerType(ITypeBinding binding) {
	if (binding == null)
		return false;

	if (!binding.isPrimitive())
		return false;

	String name= binding.getName();
	if (isIntegerNumber(name))
		return true;

	return false;
}
 
Example 12
Source File: Bindings.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public static String getRawName(ITypeBinding binding) {
	String name= binding.getName();
	if (binding.isParameterizedType() || binding.isGenericType()) {
		int idx= name.indexOf('<');
		if (idx != -1) {
			return name.substring(0, idx);
		}
	}
	return name;
}
 
Example 13
Source File: TypeEnvironment.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private TType createPrimitiveType(ITypeBinding binding) {
	String name= binding.getName();
	String[] names= PrimitiveType.NAMES;
	for (int i= 0; i < names.length; i++) {
		if (name.equals(names[i])) {
			return PRIMITIVE_TYPES[i];
		}
	}
	Assert.isTrue(false, "Primitive type " + name + "unkown");  //$NON-NLS-1$//$NON-NLS-2$
	return null;
}
 
Example 14
Source File: JavaMethodParameterCodeMining.java    From jdt-codemining with Eclipse Public License 1.0 5 votes vote down vote up
private String getParameterLabel(IMethod method, ITypeBinding calledTypeBinding) throws JavaModelException {
	ParameterMiningLabelBuilder label = new ParameterMiningLabelBuilder();
	if (showType) {
		String paramType = "";
		if (calledTypeBinding.isParameterizedType()) {
			// ex : List<String>
			ITypeBinding typeArgument = calledTypeBinding.getTypeArguments()[parameterIndex];
			paramType = typeArgument.getName();
		} else {
			paramType = method.getParameterTypes()[parameterIndex];
			paramType = Signature.getSimpleName(Signature.toString(Signature.getTypeErasure(paramType)));
			// replace [] with ... when varArgs
			if (parameterIndex == method.getParameterTypes().length - 1 && Flags.isVarargs(method.getFlags())) {
				paramType = paramType.substring(0, paramType.length() - 2) + "...";
			}
		}
		label.addParameterInfo(paramType);
	}
	if (showName) {
		String paramName = method.getParameterNames()[parameterIndex];
		if (!isArgNumber(paramName, method)) {
			label.addParameterInfo(paramName);
		}
	}
	return label.toString();

}
 
Example 15
Source File: RemoteServiceProblemFactory.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Returns a new {@link RemoteServiceProblem} for a
 * {@link RemoteServiceProblemType#MISSING_SYNC_METHOD} on an
 * <b>asynchronous</b> type.
 */
static RemoteServiceProblem newMissingSyncMethodOnAsync(
    MethodDeclaration asyncMethodDeclaration, ITypeBinding syncTypeBinding) {
  String methodName = asyncMethodDeclaration.resolveBinding().getName();
  String[] messageArgs = {syncTypeBinding.getName(), methodName};
  String[] problemArgs = {"async"};
  return RemoteServiceProblem.create(asyncMethodDeclaration.getName(),
      RemoteServiceProblemType.MISSING_SYNC_METHOD, messageArgs, problemArgs);
}
 
Example 16
Source File: RemoteServiceProblemFactory.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Returns a new {@link RemoteServiceProblem} for a
 * {@link RemoteServiceProblemType#MISSING_ASYNC_METHOD} on a
 * <b>synchronous</b> type.
 */
static RemoteServiceProblem newMissingAsyncMethodOnSync(
    MethodDeclaration syncMethodDeclaration, ITypeBinding asyncTypeBinding) {
  String[] messageArgs = {
      asyncTypeBinding.getName(),
      syncMethodDeclaration.getName().getIdentifier()};
  String[] problemArgs = {"sync"};
  return RemoteServiceProblem.create(syncMethodDeclaration.getName(),
      RemoteServiceProblemType.MISSING_ASYNC_METHOD, messageArgs, problemArgs);
}
 
Example 17
Source File: RemoteServiceProblemFactory.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Returns a new {@link RemoteServiceProblem} for a
 * {@link RemoteServiceProblemType#ASYNCCALLBACK_TYPE_ARGUMENT_MISMATCH} on a
 * <b>synchronous</b> interface.
 */
static RemoteServiceProblem newAsyncCallbackTypeArgumentMismatchOnSync(
    MethodDeclaration syncMethodDeclaration,
    ITypeBinding callbackTypeArgumentBinding) {
  String[] arguments = {
      callbackTypeArgumentBinding.getName(),
      syncMethodDeclaration.resolveBinding().getReturnType().getName()};
  final String[] problemArgs = {"sync"};
  return RemoteServiceProblem.create(syncMethodDeclaration.getReturnType2(),
      RemoteServiceProblemType.ASYNCCALLBACK_TYPE_ARGUMENT_MISMATCH,
      arguments, problemArgs);
}
 
Example 18
Source File: RemoteServiceProblemFactory.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Returns a new {@link RemoteServiceProblem} for a
 * {@link RemoteServiceProblemType#ASYNCCALLBACK_TYPE_ARGUMENT_MISMATCH} on an
 * <b>asynchronous</b> interface.
 */
static RemoteServiceProblem newAsyncCallbackTypeArgumentMismatchOnAsync(
    Type callbackTypeArgument, ITypeBinding callbackTypeArgumentBinding,
    ITypeBinding syncReturnType) {
  String[] arguments = {
      callbackTypeArgumentBinding.getName(), syncReturnType.getName()};
  final String[] problemArgs = {"async"};
  return RemoteServiceProblem.create(callbackTypeArgument,
      RemoteServiceProblemType.ASYNCCALLBACK_TYPE_ARGUMENT_MISMATCH,
      arguments, problemArgs);
}
 
Example 19
Source File: ReferenceResolvingVisitor.java    From windup with Eclipse Public License 1.0 4 votes vote down vote up
private AnnotationClassReference processAnnotation(ClassReference annotatedReference, Annotation node)
{
    final ITypeBinding typeBinding = node.resolveTypeBinding();
    final AnnotationClassReference reference;
    final String qualifiedName;
    final String packageName;
    final String className;
    final ResolutionStatus status;
    if (typeBinding != null)
    {
        status = ResolutionStatus.RESOLVED;
        qualifiedName = typeBinding.getQualifiedName();
        packageName = typeBinding.getPackage().getName();
        className = typeBinding.getName();
    }
    else
    {
        ResolveClassnameResult result = resolveClassname(node.getTypeName().toString());
        status = result.found ? ResolutionStatus.RECOVERED : ResolutionStatus.UNRESOLVED;
        qualifiedName = result.result;

        PackageAndClassName packageAndClassName = PackageAndClassName.parseFromQualifiedName(result.result);
        packageName = packageAndClassName.packageName;
        className = packageAndClassName.className;
    }

    reference = new AnnotationClassReference(
                annotatedReference,
                qualifiedName,
                packageName,
                className,
                status,
                compilationUnit.getLineNumber(node.getStartPosition()),
                compilationUnit.getColumnNumber(node.getStartPosition()),
                node.getLength(),
                node.toString());

    addAnnotationValues(annotatedReference, reference, node);

    return reference;
}
 
Example 20
Source File: JdtBasedTypeFactory.java    From xtext-eclipse with Eclipse Public License 2.0 4 votes vote down vote up
/**
 * @since 2.4
 */
protected JvmDeclaredType createType(ITypeBinding typeBinding, String handleIdentifier, List<String> path, StringBuilder fqn) {
	if (typeBinding.isAnonymous() || typeBinding.isSynthetic())
		throw new IllegalStateException("Cannot create type for anonymous or synthetic classes");

	// Creates the right type of instance based on the type of binding.
	//
	JvmGenericType jvmGenericType;
	JvmDeclaredType result;
	if (typeBinding.isAnnotation()) {
		jvmGenericType = null;
		result = TypesFactory.eINSTANCE.createJvmAnnotationType();
	} else if (typeBinding.isEnum()) {
		jvmGenericType = null;
		result = TypesFactory.eINSTANCE.createJvmEnumerationType();
	} else {
		result = jvmGenericType = TypesFactory.eINSTANCE.createJvmGenericType();
		jvmGenericType.setInterface(typeBinding.isInterface());
	}

	// Populate the information computed from the modifiers.
	//
	int modifiers = typeBinding.getModifiers();
	setTypeModifiers(result, modifiers);
	result.setDeprecated(typeBinding.isDeprecated());
	setVisibility(result, modifiers);

	// Determine the simple name and compose the fully qualified name and path, remembering the fqn length and path size so we can reset them.
	//
	String simpleName = typeBinding.getName();
	fqn.append(simpleName);
	int length = fqn.length();
	int size = path.size();
	path.add(simpleName);

	String qualifiedName = fqn.toString();
	result.internalSetIdentifier(qualifiedName);
	result.setSimpleName(simpleName);

	// Traverse the nested types using '$' as the qualified name separator.
	//
	fqn.append('$');
	createNestedTypes(typeBinding, result, handleIdentifier, path, fqn);

	// Traverse the methods using '.'as the qualifed name separator.
	//
	fqn.setLength(length);
	fqn.append('.');
	createMethods(typeBinding, handleIdentifier, path, fqn, result);
	
	createFields(typeBinding, fqn, result);

	// Set the super types.
	//
	setSuperTypes(typeBinding, qualifiedName, result);

	// If this is for a generic type, populate the type parameters.
	//
	if (jvmGenericType != null) {
		ITypeBinding[] typeParameterBindings = typeBinding.getTypeParameters();
		if (typeParameterBindings.length > 0) {
			InternalEList<JvmTypeParameter> typeParameters = (InternalEList<JvmTypeParameter>)jvmGenericType.getTypeParameters();
			for (ITypeBinding variable : typeParameterBindings) {
				typeParameters.addUnique(createTypeParameter(variable, result));
			}
		}
	}

	// Populate the annotation values.
	//
	createAnnotationValues(typeBinding, result);

	// Restore the path.
	//
	path.remove(size);

	return result;
}