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

The following examples show how to use org.eclipse.jdt.core.IType#getType() . 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: GWTTypeRefactoringSupportTest.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 6 votes vote down vote up
public void testCreateEditForInnerClass() {
  GWTTypeRefactoringSupport support = new GWTTypeRefactoringSupport();

  // Change the name of the inner class B to BBB
  IType r = rClass.getCompilationUnit().getType("R");
  IType oldType = r.getType("B");
  support.setOldElement(oldType);
  IType newType = r.getType("BBB");
  support.setNewElement(newType);

  String rawRef = "@com.hello.client.R.B::getNumber()";
  IIndexedJavaRef ref = new IndexedJsniJavaRef(JsniJavaRef.parse(rawRef));

  ReplaceEdit edit = (ReplaceEdit) support.createEdit(ref);
  assertEquals(1, edit.getOffset());
  assertEquals(20, edit.getLength());
  assertEquals("com.hello.client.R.BBB", edit.getText());
}
 
Example 2
Source File: GWTTypeRefactoringSupportTest.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 6 votes vote down vote up
public void testCreateEditPreserveDollarClassSeparator() {
  GWTTypeRefactoringSupport support = new GWTTypeRefactoringSupport();

  // Change the name of the inner class B to BBB
  IType r = rClass.getCompilationUnit().getType("R");
  IType oldType = r.getType("B");
  support.setOldElement(oldType);
  IType newType = r.getType("BBB");
  support.setNewElement(newType);

  String rawRef = "@com.hello.client.R$B::getNumber()";
  IIndexedJavaRef ref = new IndexedJsniJavaRef(JsniJavaRef.parse(rawRef));

  ReplaceEdit edit = (ReplaceEdit) support.createEdit(ref);
  assertEquals(1, edit.getOffset());
  assertEquals(20, edit.getLength());
  assertEquals("com.hello.client.R$BBB", edit.getText());
}
 
Example 3
Source File: JavaProject.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
IType findType(String fullyQualifiedName, NameLookup lookup, boolean considerSecondaryTypes, IProgressMonitor progressMonitor) throws JavaModelException {
	NameLookup.Answer answer = lookup.findType(
		fullyQualifiedName,
		false,
		NameLookup.ACCEPT_ALL,
		considerSecondaryTypes,
		true, /* wait for indexes (only if consider secondary types)*/
		false/*don't check restrictions*/,
		progressMonitor);
	if (answer == null) {
		// try to find enclosing type
		int lastDot = fullyQualifiedName.lastIndexOf('.');
		if (lastDot == -1) return null;
		IType type = findType(fullyQualifiedName.substring(0, lastDot), lookup, considerSecondaryTypes, progressMonitor);
		if (type != null) {
			type = type.getType(fullyQualifiedName.substring(lastDot+1));
			if (!type.exists()) {
				return null;
			}
		}
		return type;
	}
	return answer.type;
}
 
Example 4
Source File: Binding2JavaModel.java    From lapse-plus with GNU General Public License v3.0 5 votes vote down vote up
private static IType findTypeInType(String[] typeElements, IType jmType) {
    IType result= jmType;
    for (int i= 1; i < typeElements.length; i++) {
        result= result.getType(typeElements[i]);
        if (!result.exists())
            return null;
    }
    return result == jmType ? null : result;
}
 
Example 5
Source File: JdtBasedTypeFactory.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
private IType findTypeByHandleIdentifier() {
	IType type = (IType)JavaCore.create(handleIdentifier, workingCopyOwner);
	if (type != null) {
		for (String typeName : path) {
			type = type.getType(typeName);
			if (type == null) {
				break;
			}
		}
	}
	return type;
}
 
Example 6
Source File: PullUpRefactoringProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private RefactoringStatus checkIfTypeDeclaredIn(final IType iType, final IType type) {
	final IType typeInType= type.getType(iType.getElementName());
	if (!typeInType.exists())
		return null;
	final String[] keys= { JavaElementLabels.getTextLabel(typeInType, JavaElementLabels.ALL_FULLY_QUALIFIED), JavaElementLabels.getTextLabel(type, JavaElementLabels.ALL_FULLY_QUALIFIED)};
	final String msg= Messages.format(RefactoringCoreMessages.PullUpRefactoring_Type_declared_in_class, keys);
	final RefactoringStatusContext context= JavaStatusContext.create(typeInType);
	return RefactoringStatus.createWarningStatus(msg, context);
}
 
Example 7
Source File: NameLookup.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private IType getMemberType(IType type, String name, int dot) {
	while (dot != -1) {
		int start = dot+1;
		dot = name.indexOf('.', start);
		String typeName = name.substring(start, dot == -1 ? name.length() : dot);
		type = type.getType(typeName);
	}
	return type;
}
 
Example 8
Source File: OriginalEditorSelector.java    From xtext-eclipse with Eclipse Public License 2.0 4 votes vote down vote up
protected IType findJavaTypeForSimpleFileName(String name) {
	int index = name.lastIndexOf('.');
	if (index < 0)
		return null;
	String typeName = name.substring(0, index);
	String ext = name.substring(index + 1).toLowerCase();
	if (!ext.equals("class") && !ext.equals("java"))
		return null;
	final boolean searchForSources = ext.equals("java");
	final SearchResult result = findTypesBySimpleName(typeName, searchForSources);
	switch (result.foundTypes.size()) {
		case 1 : {
			return result.getExactMatch();
		}
		case 0 : {
			// check for nested types
			final String[] splitedName = typeName.split("\\$");
			if (splitedName.length > 1) {
				final SearchResult containerResult = findTypesBySimpleName(splitedName[0], searchForSources);
				IType candidate = null;
				for (IType currentType : containerResult.foundTypes) {
					for (int i = 1; i < splitedName.length; i++) {
						currentType = currentType.getType(splitedName[i]);
						if (currentType == null || !currentType.exists()) {
							break;
						} else if (i == splitedName.length-1) {
							if (candidate != null) {
								// multiple matches
								return null;
							}
							candidate = currentType;
						}
					}
				}
				return candidate;
			}
		}
		default : {
			return null;
		}
	}
}
 
Example 9
Source File: NewTypeWizardPage.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Hook method that gets called when the type name has changed. The method validates the
 * type name and returns the status of the validation.
 * <p>
 * Subclasses may extend this method to perform their own validation.
 * </p>
 *
 * @return the status of the validation
 */
protected IStatus typeNameChanged() {
	StatusInfo status= new StatusInfo();
	fCurrType= null;
	String typeNameWithParameters= getTypeName();
	// must not be empty
	if (typeNameWithParameters.length() == 0) {
		status.setError(NewWizardMessages.NewTypeWizardPage_error_EnterTypeName);
		return status;
	}

	String typeName= getTypeNameWithoutParameters();
	if (typeName.indexOf('.') != -1) {
		status.setError(NewWizardMessages.NewTypeWizardPage_error_QualifiedName);
		return status;
	}

	IJavaProject project= getJavaProject();
	IStatus val= validateJavaTypeName(typeName, project);
	if (val.getSeverity() == IStatus.ERROR) {
		status.setError(Messages.format(NewWizardMessages.NewTypeWizardPage_error_InvalidTypeName, val.getMessage()));
		return status;
	} else if (val.getSeverity() == IStatus.WARNING) {
		status.setWarning(Messages.format(NewWizardMessages.NewTypeWizardPage_warning_TypeNameDiscouraged, val.getMessage()));
		// continue checking
	}

	// must not exist
	if (!isEnclosingTypeSelected()) {
		IPackageFragment pack= getPackageFragment();
		if (pack != null) {
			ICompilationUnit cu= pack.getCompilationUnit(getCompilationUnitName(typeName));
			fCurrType= cu.getType(typeName);
			IResource resource= cu.getResource();

			if (resource.exists()) {
				status.setError(NewWizardMessages.NewTypeWizardPage_error_TypeNameExists);
				return status;
			}
			if (!ResourcesPlugin.getWorkspace().validateFiltered(resource).isOK()) {
				status.setError(NewWizardMessages.NewTypeWizardPage_error_TypeNameFiltered);
				return status;
			}
			URI location= resource.getLocationURI();
			if (location != null) {
				try {
					IFileStore store= EFS.getStore(location);
					if (store.fetchInfo().exists()) {
						status.setError(NewWizardMessages.NewTypeWizardPage_error_TypeNameExistsDifferentCase);
						return status;
					}
				} catch (CoreException e) {
					status.setError(Messages.format(
						NewWizardMessages.NewTypeWizardPage_error_uri_location_unkown,
						BasicElementLabels.getURLPart(Resources.getLocationString(resource))));
				}
			}
		}
	} else {
		IType type= getEnclosingType();
		if (type != null) {
			fCurrType= type.getType(typeName);
			if (fCurrType.exists()) {
				status.setError(NewWizardMessages.NewTypeWizardPage_error_TypeNameExists);
				return status;
			}
		}
	}

	if (!typeNameWithParameters.equals(typeName) && project != null) {
		if (!JavaModelUtil.is50OrHigher(project)) {
			status.setError(NewWizardMessages.NewTypeWizardPage_error_TypeParameters);
			return status;
		}
		String typeDeclaration= "class " + typeNameWithParameters + " {}"; //$NON-NLS-1$//$NON-NLS-2$
		ASTParser parser= ASTParser.newParser(ASTProvider.SHARED_AST_LEVEL);
		parser.setSource(typeDeclaration.toCharArray());
		parser.setProject(project);
		CompilationUnit compilationUnit= (CompilationUnit) parser.createAST(null);
		IProblem[] problems= compilationUnit.getProblems();
		if (problems.length > 0) {
			status.setError(Messages.format(NewWizardMessages.NewTypeWizardPage_error_InvalidTypeName, problems[0].getMessage()));
			return status;
		}
	}
	return status;
}
 
Example 10
Source File: TypeNameMatchRequestorWrapper.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
public void acceptType(int modifiers, char[] packageName, char[] simpleTypeName, char[][] enclosingTypeNames, String path, AccessRestriction access) {

	// Get type
	try {
		IType type = null;
		if (this.handleFactory != null) {
			Openable openable = this.handleFactory.createOpenable(path, this.scope);
			if (openable == null) return;
			switch (openable.getElementType()) {
				case IJavaElement.COMPILATION_UNIT:
					ICompilationUnit cu = (ICompilationUnit) openable;
					if (enclosingTypeNames != null && enclosingTypeNames.length > 0) {
						type = cu.getType(new String(enclosingTypeNames[0]));
						for (int j=1, l=enclosingTypeNames.length; j<l; j++) {
							type = type.getType(new String(enclosingTypeNames[j]));
						}
						type = type.getType(new String(simpleTypeName));
					} else {
						type = cu.getType(new String(simpleTypeName));
					}
					break;
				case IJavaElement.CLASS_FILE:
					type = ((IClassFile)openable).getType();
					break;
			}
		} else {
			int separatorIndex= path.indexOf(IJavaSearchScope.JAR_FILE_ENTRY_SEPARATOR);
			type = separatorIndex == -1
				? createTypeFromPath(path, new String(simpleTypeName), enclosingTypeNames)
				: createTypeFromJar(path, separatorIndex);
		}

		// Accept match if the type has been found
		if (type != null) {
			// hierarchy scopes require one more check:
			if (!(this.scope instanceof HierarchyScope) || ((HierarchyScope)this.scope).enclosesFineGrained(type)) {

				// Create the match
				final JavaSearchTypeNameMatch match = new JavaSearchTypeNameMatch(type, modifiers);

				// Update match accessibility
				if(access != null) {
					switch (access.getProblemId()) {
						case IProblem.ForbiddenReference:
							match.setAccessibility(IAccessRule.K_NON_ACCESSIBLE);
							break;
						case IProblem.DiscouragedReference:
							match.setAccessibility(IAccessRule.K_DISCOURAGED);
							break;
					}
				}

				// Accept match
				this.requestor.acceptTypeNameMatch(match);
			}
		}
	} catch (JavaModelException e) {
		// skip
	}
}