Java Code Examples for org.eclipse.jdt.core.IType#getElementName()

The following examples show how to use org.eclipse.jdt.core.IType#getElementName() . 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: AbstractHierarchyViewerSorter.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private int compareInHierarchy(IType def1, IType def2) {
	if (JavaModelUtil.isSuperType(getHierarchy(def1), def2, def1)) {
		return 1;
	} else if (JavaModelUtil.isSuperType(getHierarchy(def2), def1, def2)) {
		return -1;
	}
	// interfaces after classes
	try {
		int flags1= getTypeFlags(def1);
		int flags2= getTypeFlags(def2);
		if (Flags.isInterface(flags1)) {
			if (!Flags.isInterface(flags2)) {
				return 1;
			}
		} else if (Flags.isInterface(flags2)) {
			return -1;
		}
	} catch (JavaModelException e) {
		// ignore
	}
	String name1= def1.getElementName();
	String name2= def2.getElementName();

	return getComparator().compare(name1, name2);
}
 
Example 2
Source File: TraceForTypeRootProvider.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
protected String getJavaSimpleFileName(final ITypeRoot derivedResource) {
	IType type = derivedResource.findPrimaryType();
	if (type == null)
		return null;
	String sourceName = ((BinaryType) type).getSourceFileName(null);
	if (sourceName == null)
		return null;

	// the primary source in the .class file is .java (JSR-45 aka SMAP scenario)
	if (sourceName.endsWith(".java")) {
		return sourceName;
	}

	// xtend-as-primary-source-scenario.
	if (sourceName.endsWith(".xtend")) {
		String name = type.getElementName();
		int index = name.indexOf("$");
		if (index > 0)
			name = name.substring(0, index);
		return name + ".java";
	}
	return null;
}
 
Example 3
Source File: CreateMethodOperation.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * @see CreateTypeMemberOperation#verifyNameCollision
 */
protected IJavaModelStatus verifyNameCollision() {
	if (this.createdNode != null) {
		IType type = getType();
		String name;
		if (((MethodDeclaration) this.createdNode).isConstructor())
			name = type.getElementName();
		else
			name = getASTNodeName();
		String[] types = convertASTMethodTypesToSignatures();
		if (type.getMethod(name, types).exists()) {
			return new JavaModelStatus(
				IJavaModelStatusConstants.NAME_COLLISION,
				Messages.bind(Messages.status_nameCollision, name));
		}
	}
	return JavaModelStatus.VERIFIED_OK;
}
 
Example 4
Source File: MatchLocator.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Creates an IImportDeclaration from the given import statement
 */
protected IJavaElement createImportHandle(ImportReference importRef) {
	char[] importName = CharOperation.concatWith(importRef.getImportName(), '.');
	if ((importRef.bits & ASTNode.OnDemand) != 0)
		importName = CharOperation.concat(importName, ".*" .toCharArray()); //$NON-NLS-1$
	Openable openable = this.currentPossibleMatch.openable;
	if (openable instanceof CompilationUnit)
		return ((CompilationUnit) openable).getImport(new String(importName));

	// binary types do not contain import statements so just answer the top-level type as the element
	IType binaryType = ((ClassFile) openable).getType();
	String typeName = binaryType.getElementName();
	int lastDollar = typeName.lastIndexOf('$');
	if (lastDollar == -1) return binaryType;
	return createTypeHandle(typeName.substring(0, lastDollar));
}
 
Example 5
Source File: ChangeCollector.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private boolean hasSuperTypeChange(IType type) throws JavaModelException {
	// check super class
	IType superclass = this.hierarchy.getSuperclass(type);
	String existingSuperclassName = superclass == null ? null : superclass.getElementName();
	String newSuperclassName = type.getSuperclassName();
	if (existingSuperclassName != null && !existingSuperclassName.equals(newSuperclassName)) {
		return true;
	}

	// check super interfaces
	IType[] existingSuperInterfaces = this.hierarchy.getSuperInterfaces(type);
	String[] newSuperInterfaces = type.getSuperInterfaceNames();
	if (existingSuperInterfaces.length != newSuperInterfaces.length) {
		return true;
	}
	for (int i = 0, length = newSuperInterfaces.length; i < length; i++) {
		String superInterfaceName = newSuperInterfaces[i];
		if (!superInterfaceName.equals(newSuperInterfaces[i])) {
			return true;
		}
	}

	return false;
}
 
Example 6
Source File: CompareToMethodSkeleton.java    From jenerate with Eclipse Public License 1.0 6 votes vote down vote up
private String createCompareToMethod(IType objectClass, CompareToGenerationData data, boolean generify,
        boolean addOverride, String methodContent) {

    StringBuffer content = new StringBuffer();
    if (data.generateComment()) {
        content.append("/**\n");
        content.append(" * {@inheritDoc}\n");
        content.append(" */\n");
    }

    if (addOverride) {
        content.append("@Override\n");
    }

    String className = objectClass.getElementName();
    if (generify) {
        content.append("public int compareTo(final " + className + " other) {\n");
    } else {
        content.append("public int compareTo(final Object other) {\n");
    }
    content.append(methodContent);
    content.append("}\n\n");

    return content.toString();
}
 
Example 7
Source File: Bug403554Test.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public void setUp() throws Exception {
	super.setUp();
	IJavaProject project = getJavaProject(null);
	IType type = project.findType(ArrayList.class.getName());
	IMethod method = type.getMethod("subList", new String[] { "I", "I" });
	while (!method.exists()) {
		String superclassName = type.getSuperclassName();
		int idx = superclassName.indexOf("<");
		if (idx != -1) {
			superclassName = superclassName.substring(0, idx);
		}
		type = project.findType(superclassName);
		method = type.getMethod("subList", new String[] { "I", "I" });
	}
	declarator = type.getElementName();
}
 
Example 8
Source File: GuavaCompareToMethodContent.java    From jenerate with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public String getMethodContent(IType objectClass, CompareToGenerationData data) throws Exception {
    boolean generify = MethodGenerations.generifyCompareTo(objectClass,
            isComparableImplementedOrExtendedInSupertype(objectClass), getPreferencesManager());
    StringBuffer content = new StringBuffer();
    String other = "other";
    if (!generify) {
        String className = objectClass.getElementName();
        content.append(className);
        content.append(" castOther = (");
        content.append(className);
        content.append(") other;\n");
        other = "castOther";
    }

    content.append("return ComparisonChain.start()");
    IField[] checkedFields = data.getCheckedFields();
    for (IField checkedField : checkedFields) {
        content.append(".compare(");
        String fieldName = MethodContentGenerations.getFieldAccessorString(checkedField,
                data.useGettersInsteadOfFields());
        content.append(fieldName);
        content.append(", ");
        content.append(other);
        content.append(".");
        content.append(fieldName);
        content.append(")");
    }
    content.append(".result();\n");
    return content.toString();
}
 
Example 9
Source File: MoveInnerToTopRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private String getInitialNameForEnclosingInstanceField() {
	IType enclosingType= fType.getDeclaringType();
	if (enclosingType == null)
		return ""; //$NON-NLS-1$
	String[] suggestedNames= StubUtility.getFieldNameSuggestions(fType.getDeclaringType(), getEnclosingInstanceAccessModifiers(), getFieldNames(fType));
	if (suggestedNames.length > 0)
		return suggestedNames[0];
	String name= enclosingType.getElementName();
	if (name.equals("")) //$NON-NLS-1$
		return ""; //$NON-NLS-1$
	return Character.toLowerCase(name.charAt(0)) + name.substring(1);
}
 
Example 10
Source File: MoveInnerToTopRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private static AbstractTypeDeclaration findTypeDeclaration(IType enclosing, AbstractTypeDeclaration[] declarations) {
	String typeName= enclosing.getElementName();
	for (int i= 0; i < declarations.length; i++) {
		AbstractTypeDeclaration declaration= declarations[i];
		if (declaration.getName().getIdentifier().equals(typeName))
			return declaration;
	}
	return null;
}
 
Example 11
Source File: ChangeCollector.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private void addTypeAddition(IType type, SimpleDelta existingDelta) throws JavaModelException {
	if (existingDelta != null) {
		switch (existingDelta.getKind()) {
			case IJavaElementDelta.REMOVED:
				// REMOVED then ADDED
				boolean hasChange = false;
				if (hasSuperTypeChange(type)) {
					existingDelta.superTypes();
					hasChange = true;
				}
				if (hasVisibilityChange(type)) {
					existingDelta.modifiers();
					hasChange = true;
				}
				if (!hasChange) {
					this.changes.remove(type);
				}
				break;
				// CHANGED then ADDED
				// or ADDED then ADDED: should not happen
		}
	} else {
		// check whether the type addition affects the hierarchy
		String typeName = type.getElementName();
		if (this.hierarchy.hasSupertype(typeName)
				|| this.hierarchy.subtypesIncludeSupertypeOf(type)
				|| this.hierarchy.missingTypes.contains(typeName)) {
			SimpleDelta delta = new SimpleDelta();
			delta.added();
			this.changes.put(type, delta);
		}
	}
}
 
Example 12
Source File: DAOExpressionProvider.java    From bonita-studio with GNU General Public License v2.0 5 votes vote down vote up
protected Expression createExpression(final IType daoType) {
    final Expression expression = ExpressionFactory.eINSTANCE.createExpression();
    String elementName = daoType.getElementName();
    elementName = Character.toLowerCase(elementName.charAt(0)) + elementName.substring(1, elementName.length());
    expression.setName(elementName);
    expression.setContent(elementName);
    expression.setReturnType(daoType.getFullyQualifiedName());
    expression.setReturnTypeFixed(true);
    expression.setType(getExpressionType());
    return expression;
}
 
Example 13
Source File: CompareToMethodSkeleton.java    From jenerate with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public String[] getMethodArguments(IType objectClass) throws Exception {
    if (MethodGenerations.generifyCompareTo(objectClass, isComparableImplementedOrExtendedInSupertype(objectClass),
            preferencesManager)) {
        String elementName = objectClass.getElementName();
        return new String[] { createArgument(elementName) };
    }
    return new String[] { createArgument("Object") };
}
 
Example 14
Source File: CompareToMethodSkeleton.java    From jenerate with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public String getMethod(IType objectClass, CompareToGenerationData data, String methodContent) throws Exception {
    boolean implementedOrExtendedInSuperType = isComparableImplementedOrExtendedInSupertype(objectClass);
    boolean generify = MethodGenerations.generifyCompareTo(objectClass, implementedOrExtendedInSuperType,
            preferencesManager);
    boolean addOverride = addOverride(objectClass);
    if (!implementedOrExtendedInSuperType) {
        String interfaceName = "Comparable";
        if (generify) {
            interfaceName = "Comparable<" + objectClass.getElementName() + ">";
        }
        javaInterfaceCodeAppender.addSuperInterface(objectClass, interfaceName);
    }
    return createCompareToMethod(objectClass, data, generify, addOverride, methodContent);
}
 
Example 15
Source File: UiBinderResourceCreator.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 5 votes vote down vote up
protected static String createUiBinderStaticField(IType ownerClass,
    ImportsManager imports) {
  String uiBinderTypeName = ownerClass.getElementName() + "UiBinder";

  StringBuilder sb = new StringBuilder();
  sb.append("private static ");
  sb.append(uiBinderTypeName);
  sb.append(" uiBinder = ");
  sb.append(imports.addImport(GWT_TYPE_NAME));
  sb.append(".create(");
  sb.append(uiBinderTypeName);
  sb.append(".class);");

  return sb.toString();
}
 
Example 16
Source File: JdtTypeProvider.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * @since 2.9
 */
/* @Nullable */
protected IMirror createMirror(/* @NonNull */ IType type) {
	String elementName = type.getElementName();
	if (!elementName.equals(type.getTypeQualifiedName())) {
		// workaround for bug in jdt with binary type names that start with a $ dollar sign
		// e.g. $ImmutableList
		// it manifests itself in a way that allows to retrieve ITypes but one cannot obtain bindings for that type
		return null;
	}
	return new JdtTypeMirror(type, typeFactory, services);
}
 
Example 17
Source File: MethodContentGenerations.java    From jenerate with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Creates the equals method content given a certain equals method name for delegation
 * 
 * @param equalsMethodName the equals method name that process the equality
 * @param data the data to extract configuration from
 * @param objectClass the class where the equals method is being generated
 * @return the equals method content
 * @throws JavaModelException if a problem occurs during the code generation.
 */
public static String createEqualsContent(String equalsMethodName, EqualsHashCodeGenerationData data,
        IType objectClass) throws JavaModelException {
    StringBuffer content = new StringBuffer();
    boolean useBlockInIfStatements = data.useBlockInIfStatements();
    String elementName = objectClass.getElementName();
    if (data.appendSuper()) {
        content.append("if (!super.equals(other))");
        content.append(useBlockInIfStatements ? "{\n" : "");
        content.append(" return false;");
        content.append(useBlockInIfStatements ? "\n}\n" : "");
    }
    if (data.useClassCast()) {
        content.append(elementName);
        content.append(" castOther = ");
        content.append(elementName);
        content.append(".class.cast(other);\n");
    } else {
        content.append(elementName);
        content.append(" castOther = (");
        content.append(elementName);
        content.append(") other;\n");
    }
    content.append("return ");
    String prefix = "";
    IField[] checkedFields = data.getCheckedFields();
    for (IField checkedField : checkedFields) {
        content.append(prefix);
        prefix = " && ";
        content.append("Objects.");
        content.append(equalsMethodName);
        content.append("(");
        String fieldName = MethodContentGenerations.getFieldAccessorString(checkedField,
                data.useGettersInsteadOfFields());
        content.append(fieldName);
        content.append(", castOther.");
        content.append(fieldName);
        content.append(")");
    }
    content.append(";\n");
    return content.toString();
}
 
Example 18
Source File: ChangeUtil.java    From eclipse.jdt.ls with Eclipse Public License 2.0 4 votes vote down vote up
private static boolean isPrimaryType(IType type) {
	String cuName = type.getCompilationUnit().getElementName();
	String typeName = type.getElementName();
	return type.getDeclaringType() == null && JavaCore.removeJavaLikeExtension(cuName).equals(typeName);
}
 
Example 19
Source File: RefactoringHandleTransplanter.java    From eclipse.jdt.ls with Eclipse Public License 2.0 4 votes vote down vote up
private String resolveTypeName(IType type) {
	return type.equals(fOldType) ? fNewType.getElementName() : type.getElementName();
}
 
Example 20
Source File: GetterSetterUtil.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Create a stub for a getter of the given field using getter/setter templates. The resulting code
 * has to be formatted and indented.
 * @param field The field to create a getter for
 * @param setterName The chosen name for the setter
 * @param addComments If <code>true</code>, comments will be added.
 * @param flags The flags signaling visibility, if static, synchronized or final
 * @return Returns the generated stub.
 * @throws CoreException when stub creation failed
 */
public static String getSetterStub(IField field, String setterName, boolean addComments, int flags) throws CoreException {

	String fieldName= field.getElementName();
	IType parentType= field.getDeclaringType();

	String returnSig= field.getTypeSignature();
	String typeName= Signature.toString(returnSig);

	IJavaProject project= field.getJavaProject();

	String accessorName= StubUtility.getBaseName(field);
	String argname= StubUtility.suggestArgumentName(project, accessorName, EMPTY);

	boolean isStatic= Flags.isStatic(flags);
	boolean isSync= Flags.isSynchronized(flags);
	boolean isFinal= Flags.isFinal(flags);

	String lineDelim= "\n"; // Use default line delimiter, as generated stub has to be formatted anyway //$NON-NLS-1$
	StringBuffer buf= new StringBuffer();
	if (addComments) {
		String comment= CodeGeneration.getSetterComment(field.getCompilationUnit(), parentType.getTypeQualifiedName('.'), setterName, field.getElementName(), typeName, argname, accessorName, lineDelim);
		if (comment != null) {
			buf.append(comment);
			buf.append(lineDelim);
		}
	}
	buf.append(JdtFlags.getVisibilityString(flags));
	buf.append(' ');
	if (isStatic)
		buf.append("static "); //$NON-NLS-1$
	if (isSync)
		buf.append("synchronized "); //$NON-NLS-1$
	if (isFinal)
		buf.append("final "); //$NON-NLS-1$

	buf.append("void "); //$NON-NLS-1$
	buf.append(setterName);
	buf.append('(');
	buf.append(typeName);
	buf.append(' ');
	buf.append(argname);
	buf.append(") {"); //$NON-NLS-1$
	buf.append(lineDelim);

	boolean useThis= StubUtility.useThisForFieldAccess(project);
	if (argname.equals(fieldName) || (useThis && !isStatic)) {
		if (isStatic)
			fieldName= parentType.getElementName() + '.' + fieldName;
		else
			fieldName= "this." + fieldName; //$NON-NLS-1$
	}
	String body= CodeGeneration.getSetterMethodBodyContent(field.getCompilationUnit(), parentType.getTypeQualifiedName('.'), setterName, fieldName, argname, lineDelim);
	if (body != null) {
		buf.append(body);
	}
	buf.append("}"); //$NON-NLS-1$
	buf.append(lineDelim);
	return buf.toString();
}