Java Code Examples for org.eclipse.jdt.core.IField#exists()

The following examples show how to use org.eclipse.jdt.core.IField#exists() . 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: JDTUtils.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Resolves the field described by the receiver and returns it if found. Returns
 * <code>null</code> if no corresponding member can be found.
 *
 * @param proposal
 *            - completion proposal
 * @param javaProject
 *            - Java project
 *
 * @return the resolved field or <code>null</code> if none is found
 * @throws JavaModelException
 *             if accessing the java model fails
 */
public static IField resolveField(CompletionProposal proposal, IJavaProject javaProject) throws JavaModelException {
	char[] declarationSignature = proposal.getDeclarationSignature();
	// for synthetic fields on arrays, declaration signatures may be null
	// TODO remove when https://bugs.eclipse.org/bugs/show_bug.cgi?id=84690 gets fixed
	if (declarationSignature == null) {
		return null;
	}
	String typeName = SignatureUtil.stripSignatureToFQN(String.valueOf(declarationSignature));
	IType type = javaProject.findType(typeName);
	if (type != null) {
		String name = String.valueOf(proposal.getName());
		IField field = type.getField(name);
		if (field.exists()) {
			return field;
		}
	}

	return null;
}
 
Example 2
Source File: RenameFieldProcessor.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
private RefactoringStatus checkNestedHierarchy(IType type) throws CoreException {
	IType[] nestedTypes= type.getTypes();
	if (nestedTypes == null) {
		return null;
	}
	RefactoringStatus result= new RefactoringStatus();
	for (int i= 0; i < nestedTypes.length; i++){
		IField otherField= nestedTypes[i].getField(getNewElementName());
		if (otherField.exists()){
			String msg= Messages.format(
				RefactoringCoreMessages.RenameFieldRefactoring_hiding,
				new String[]{ BasicElementLabels.getJavaElementName(fField.getElementName()), BasicElementLabels.getJavaElementName(getNewElementName()), BasicElementLabels.getJavaElementName(nestedTypes[i].getFullyQualifiedName('.'))});
			result.addWarning(msg, JavaStatusContext.create(otherField));
		}
		result.merge(checkNestedHierarchy(nestedTypes[i]));
	}
	return result;
}
 
Example 3
Source File: PropertiesQuickAssistProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private static boolean getRenameKeysProposals(PropertiesAssistContext invocationContext, ArrayList<ICompletionProposal> resultingCollections)
		throws BadLocationException, BadPartitioningException {
	ISourceViewer sourceViewer= invocationContext.getSourceViewer();
	IDocument document= invocationContext.getDocument();
	int selectionOffset= invocationContext.getOffset();
	int selectionLength= invocationContext.getLength();
	IField field= null;

	IType accessorClass= invocationContext.getAccessorType();
	if (accessorClass == null || !isEclipseNLSUsed(accessorClass))
		return false;

	List<String> keys= getKeysFromSelection(document, selectionOffset, selectionLength);
	if (keys == null || keys.size() != 1)
		return false;

	field= accessorClass.getField(keys.get(0));
	if (!field.exists())
		return false;
	if (resultingCollections == null)
		return true;

	String name= PropertiesFileEditorMessages.PropertiesCorrectionProcessor_rename_in_workspace;
	resultingCollections.add(new RenameKeyProposal(name, 5, JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE), field, sourceViewer.getTextWidget().getShell()));
	return true;
}
 
Example 4
Source File: RefactoringAvailabilityTester.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
public static boolean isGeneralizeTypeAvailable(final IStructuredSelection selection) throws JavaModelException {
	if (selection.size() == 1) {
		final Object element= selection.getFirstElement();
		if (element instanceof IMethod) {
			final IMethod method= (IMethod) element;
			if (!method.exists())
				return false;
			final String type= method.getReturnType();
			if (PrimitiveType.toCode(Signature.toString(type)) == null)
				return Checks.isAvailable(method);
		} else if (element instanceof IField) {
			final IField field= (IField) element;
			if (!field.exists())
				return false;
			if (!JdtFlags.isEnum(field))
				return Checks.isAvailable(field);
		}
	}
	return false;
}
 
Example 5
Source File: RenameFieldProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private RefactoringStatus checkEnclosingHierarchy() {
	IType current= fField.getDeclaringType();
	if (Checks.isTopLevel(current))
		return null;
	RefactoringStatus result= new RefactoringStatus();
	while (current != null){
		IField otherField= current.getField(getNewElementName());
		if (otherField.exists()){
			String msg= Messages.format(RefactoringCoreMessages.RenameFieldRefactoring_hiding2,
			 	new String[]{ BasicElementLabels.getJavaElementName(getNewElementName()), BasicElementLabels.getJavaElementName(current.getFullyQualifiedName('.')), BasicElementLabels.getJavaElementName(otherField.getElementName())});
			result.addWarning(msg, JavaStatusContext.create(otherField));
		}
		current= current.getDeclaringType();
	}
	return result;
}
 
Example 6
Source File: FieldProposalInfo.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Resolves the member described by the receiver and returns it if found.
 * Returns <code>null</code> if no corresponding member can be found.
 *
 * @return the resolved member or <code>null</code> if none is found
 * @throws JavaModelException if accessing the java model fails
 */
@Override
protected IMember resolveMember() throws JavaModelException {
	char[] declarationSignature= fProposal.getDeclarationSignature();
	// for synthetic fields on arrays, declaration signatures may be null
	// TODO remove when https://bugs.eclipse.org/bugs/show_bug.cgi?id=84690 gets fixed
	if (declarationSignature == null)
		return null;
	String typeName= SignatureUtil.stripSignatureToFQN(String.valueOf(declarationSignature));
	IType type= fJavaProject.findType(typeName);
	if (type != null) {
		String name= String.valueOf(fProposal.getName());
		IField field= type.getField(name);
		if (field.exists())
			return field;
	}

	return null;
}
 
Example 7
Source File: RenameTypeWizardSimilarElementsPage.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private IStatus validateSettings() {
	final String name= fNameField.getText();
	if (name.length() == 0) {
		return new StatusInfo(IStatus.ERROR, RefactoringMessages.RenameTypeWizardSimilarElementsPage_name_empty);
	}
	IStatus status= JavaConventionsUtil.validateIdentifier(name, fElementToEdit);
	if (status.matches(IStatus.ERROR))
		return status;
	if (!Checks.startsWithLowerCase(name))
		return new StatusInfo(IStatus.WARNING, RefactoringMessages.RenameTypeWizardSimilarElementsPage_name_should_start_lowercase);

	if (fElementToEdit instanceof IMember && ((IMember) fElementToEdit).getDeclaringType() != null) {
		IType type= ((IMember) fElementToEdit).getDeclaringType();
		if (fElementToEdit instanceof IField) {
			final IField f= type.getField(name);
			if (f.exists())
				return new StatusInfo(IStatus.ERROR, RefactoringMessages.RenameTypeWizardSimilarElementsPage_field_exists);
		}
		if (fElementToEdit instanceof IMethod) {
			final IMethod m= type.getMethod(name, ((IMethod) fElementToEdit).getParameterTypes());
			if (m.exists())
				return new StatusInfo(IStatus.ERROR, RefactoringMessages.RenameTypeWizardSimilarElementsPage_method_exists);
		}
	}

	// cannot check local variables; no .getLocalVariable(String) in IMember

	return StatusInfo.OK_STATUS;
}
 
Example 8
Source File: Binding2JavaModel.java    From lapse-plus with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Converts the given <code>IVariableBinding</code> into a <code>IField</code>
 * using the classpath defined by the given Java project. Returns <code>null</code>
 * if the conversion isn't possible.
 */
public static IField find(IVariableBinding field, IJavaProject in) throws JavaModelException {
    IType declaringClass = find(field.getDeclaringClass(), in);
    if (declaringClass == null)
        return null;
    IField foundField= declaringClass.getField(field.getName());
    if (! foundField.exists())
        return null;
    return foundField;
}
 
Example 9
Source File: InlineConstantRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private RefactoringStatus findField() {
	fField= (IField) ((IVariableBinding) fSelectedConstantName.resolveBinding()).getJavaElement();
	if (fField != null && ! fField.exists())
		return RefactoringStatus.createStatus(RefactoringStatus.FATAL, RefactoringCoreMessages.InlineConstantRefactoring_local_anonymous_unsupported, null, Corext.getPluginId(), RefactoringStatusCodes.LOCAL_AND_ANONYMOUS_NOT_SUPPORTED, null);

	return null;
}
 
Example 10
Source File: RenameFieldProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private SearchResultGroup[] getNewReferences(IProgressMonitor pm, RefactoringStatus status, WorkingCopyOwner owner, ICompilationUnit[] newWorkingCopies) throws CoreException {
	pm.beginTask("", 2); //$NON-NLS-1$
	ICompilationUnit declaringCuWorkingCopy= RenameAnalyzeUtil.findWorkingCopyForCu(newWorkingCopies, fField.getCompilationUnit());
	if (declaringCuWorkingCopy == null)
		return new SearchResultGroup[0];

	IField field= getFieldInWorkingCopy(declaringCuWorkingCopy, getNewElementName());
	if (field == null || ! field.exists())
		return new SearchResultGroup[0];

	CollectingSearchRequestor requestor= null;
	if (fDelegateUpdating && RefactoringAvailabilityTester.isDelegateCreationAvailable(getField())) {
		// There will be two new matches inside the delegate (the invocation
		// and the javadoc) which are OK and must not be reported.
		final IField oldField= getFieldInWorkingCopy(declaringCuWorkingCopy, getCurrentElementName());
		requestor= new CollectingSearchRequestor() {
			@Override
			public void acceptSearchMatch(SearchMatch match) throws CoreException {
				if (!oldField.equals(match.getElement()))
					super.acceptSearchMatch(match);
			}
		};
	} else
		requestor= new CollectingSearchRequestor();

	SearchPattern newPattern= SearchPattern.createPattern(field, IJavaSearchConstants.REFERENCES);
	IJavaSearchScope scope= RefactoringScopeFactory.create(fField, true, true);
	return RefactoringSearchEngine.search(newPattern, owner, scope, requestor, new SubProgressMonitor(pm, 1), status);
}
 
Example 11
Source File: PullUpRefactoringProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private RefactoringStatus checkIfFieldDeclaredIn(final IField iField, final IType type) {
	final IField fieldInType= type.getField(iField.getElementName());
	if (!fieldInType.exists())
		return null;
	final String[] keys= { JavaElementLabels.getTextLabel(fieldInType, JavaElementLabels.ALL_FULLY_QUALIFIED), JavaElementLabels.getTextLabel(type, JavaElementLabels.ALL_FULLY_QUALIFIED)};
	final String msg= Messages.format(RefactoringCoreMessages.PullUpRefactoring_Field_declared_in_class, keys);
	final RefactoringStatusContext context= JavaStatusContext.create(fieldInType);
	return RefactoringStatus.createWarningStatus(msg, context);
}
 
Example 12
Source File: MemberCheckUtil.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private static void checkFieldInType(IType destinationType, RefactoringStatus result, IField field) throws JavaModelException {
	IField destinationTypeField= destinationType.getField(field.getElementName());
	if (! destinationTypeField.exists())
		return;
	String message= Messages.format(RefactoringCoreMessages.MemberCheckUtil_field_exists,
			new String[]{ BasicElementLabels.getJavaElementName(field.getElementName()), getQualifiedLabel(destinationType)});
	RefactoringStatusContext context= JavaStatusContext.create(destinationType.getCompilationUnit(), destinationTypeField.getSourceRange());
	result.addError(message, context);
}
 
Example 13
Source File: JavaModelSearch.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 5 votes vote down vote up
public static IField findField(IType type, String fieldName) {
  IField field = type.getField(fieldName);
  if (field.exists()) {
    return field;
  }

  return null;
}
 
Example 14
Source File: JavaElementLabelComposer.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Appends the style label for a field. Considers the F_* flags.
 *
 * @param field the element to render
 * @param flags the rendering flags. Flags with names starting with 'F_' are considered.
 */
public void appendFieldLabel(IField field, long flags) {
	try {

		if (getFlag(flags, JavaElementLabels.F_PRE_TYPE_SIGNATURE) && field.exists() && !Flags.isEnum(field.getFlags())) {
			if (getFlag(flags, JavaElementLabels.USE_RESOLVED) && field.isResolved()) {
				appendTypeSignatureLabel(field, new BindingKey(field.getKey()).toSignature(), flags);
			} else {
				appendTypeSignatureLabel(field, field.getTypeSignature(), flags);
			}
			fBuilder.append(' ');
		}

		// qualification
		if (getFlag(flags, JavaElementLabels.F_FULLY_QUALIFIED)) {
			appendTypeLabel(field.getDeclaringType(), JavaElementLabels.T_FULLY_QUALIFIED | (flags & QUALIFIER_FLAGS));
			fBuilder.append('.');
		}
		fBuilder.append(getElementName(field));

		if (getFlag(flags, JavaElementLabels.F_APP_TYPE_SIGNATURE) && field.exists() && !Flags.isEnum(field.getFlags())) {
			fBuilder.append(JavaElementLabels.DECL_STRING);
			if (getFlag(flags, JavaElementLabels.USE_RESOLVED) && field.isResolved()) {
				appendTypeSignatureLabel(field, new BindingKey(field.getKey()).toSignature(), flags);
			} else {
				appendTypeSignatureLabel(field, field.getTypeSignature(), flags);
			}
		}

		// post qualification
		if (getFlag(flags, JavaElementLabels.F_POST_QUALIFIED)) {
			fBuilder.append(JavaElementLabels.CONCAT_STRING);
			appendTypeLabel(field.getDeclaringType(), JavaElementLabels.T_FULLY_QUALIFIED | (flags & QUALIFIER_FLAGS));
		}

	} catch (JavaModelException e) {
		JavaLanguageServerPlugin.logException("", e); // NotExistsException will not reach this point
	}
}
 
Example 15
Source File: RenameFieldProcessor.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public RefactoringStatus checkInitialConditions(IProgressMonitor pm) throws CoreException {
	IField primary= (IField) fField.getPrimaryElement();
	if (primary == null || !primary.exists()) {
		String message= Messages.format(RefactoringCoreMessages.RenameFieldRefactoring_deleted, BasicElementLabels.getFileName(fField.getCompilationUnit()));
		return RefactoringStatus.createFatalErrorStatus(message);
	}
	fField= primary;

	return Checks.checkIfCuBroken(fField);
}
 
Example 16
Source File: PropertiesQuickAssistProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
private static boolean getCreateFieldsInAccessorClassProposals(PropertiesAssistContext invocationContext, ArrayList<ICompletionProposal> resultingCollections)
		throws BadLocationException, BadPartitioningException {
	IDocument document= invocationContext.getDocument();
	int selectionOffset= invocationContext.getOffset();
	int selectionLength= invocationContext.getLength();
	List<String> fields= new ArrayList<String>();

	IType accessorClass= invocationContext.getAccessorType();
	if (accessorClass == null || !isEclipseNLSUsed(accessorClass))
		return false;

	List<String> keys= getKeysFromSelection(document, selectionOffset, selectionLength);
	if (keys == null || keys.size() == 0)
		return false;

	for (Iterator<String> iterator= keys.iterator(); iterator.hasNext();) {
		String key= iterator.next();
		if (!isValidJavaIdentifier(key))
			continue;
		IField field= accessorClass.getField(key);
		if (field.exists())
			continue;
		if (resultingCollections == null)
			return true;
		fields.add(key);
	}

	if (fields.size() == 0)
		return false;

	ICompilationUnit cu= accessorClass.getCompilationUnit();
	try {
		Change change= AccessorClassModifier.addFields(cu, fields);
		String name= Messages.format(fields.size() == 1 ? PropertiesFileEditorMessages.PropertiesCorrectionProcessor_create_field_in_accessor_label : PropertiesFileEditorMessages.PropertiesCorrectionProcessor_create_fields_in_accessor_label, BasicElementLabels.getFileName(cu));
		resultingCollections.add(new CUCorrectionProposal(name, cu, (TextChange) change, 5, JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE)));
	} catch (CoreException e) {
		JavaPlugin.log(e);
		return false;
	}
	return true;
}
 
Example 17
Source File: JavaContext.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Adds a static import for the member with name <code>qualifiedMemberName</code>. The member is
 * either a static field or a static method or a '*' to import all static members of a type.
 *
 * @param qualifiedMemberName the fully qualified name of the member to import or a qualified type
 * 			name plus a '.*' suffix.
 * @return returns either the simple member name if the import was successful or else the qualified name.
 * @since 3.4
 */
public String addStaticImport(String qualifiedMemberName) {
	if (isReadOnly())
		return qualifiedMemberName;

	ICompilationUnit cu= getCompilationUnit();
	if (cu == null)
		return qualifiedMemberName;

	int memberOffset= qualifiedMemberName.lastIndexOf('.');
	if (memberOffset == -1)
		return qualifiedMemberName;

	String typeName= qualifiedMemberName.substring(0, memberOffset);
	String memberName= qualifiedMemberName.substring(memberOffset + 1, qualifiedMemberName.length());
	try {
		boolean isField;
		if ("*".equals(memberName)) { //$NON-NLS-1$
			isField= true;
		} else {
			IJavaProject javaProject= cu.getJavaProject();

			IType type= javaProject.findType(typeName);
			if (type == null)
				return qualifiedMemberName;

			IField field= type.getField(memberName);
			if (field.exists()) {
				isField= true;
			} else if (hasMethod(type, memberName)) {
				isField= false;
			} else {
				return qualifiedMemberName;
			}
		}

		CompilationUnit root= getASTRoot(cu);
		if (fImportRewrite == null) {
			if (root == null) {
				fImportRewrite= StubUtility.createImportRewrite(cu, true);
			} else {
				fImportRewrite= StubUtility.createImportRewrite(root, true);
			}
		}

		ImportRewriteContext context;
		if (root == null)
			context= null;
		else
			context= new ContextSensitiveImportRewriteContext(root, getCompletionOffset(), fImportRewrite);

		return fImportRewrite.addStaticImport(typeName, memberName, isField, context);
	} catch (JavaModelException e) {
		handleException(null, e);
		return typeName;
	}
}
 
Example 18
Source File: RefactoringAvailabilityTester.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
public static boolean isDelegateCreationAvailable(final IField field) throws JavaModelException {
	return field.exists() && (Flags.isStatic(field.getFlags()) && Flags.isFinal(field.getFlags()) /*
	 * &&
	 * hasInitializer(field)
	 */);
}
 
Example 19
Source File: RefactoringAvailabilityTester.java    From eclipse.jdt.ls with Eclipse Public License 2.0 4 votes vote down vote up
public static boolean isDelegateCreationAvailable(final IField field) throws JavaModelException {
	return field.exists() && (Flags.isStatic(field.getFlags()) && Flags.isFinal(field.getFlags()) /*
																									* &&
																									* hasInitializer(field)
																									*/);
}
 
Example 20
Source File: PropertiesQuickAssistProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
private static boolean getRemovePropertiesProposals(PropertiesAssistContext invocationContext, ArrayList<ICompletionProposal> resultingCollections)
		throws BadLocationException, BadPartitioningException {
	IDocument document= invocationContext.getDocument();
	int selectionOffset= invocationContext.getOffset();
	int selectionLength= invocationContext.getLength();
	List<String> fields= new ArrayList<String>();

	IFile file= invocationContext.getFile();
	if (file == null)
		return false;

	IType accessorClass= invocationContext.getAccessorType();
	if (accessorClass == null || !isEclipseNLSUsed(accessorClass))
		return false;

	List<String> keys= getKeysFromSelection(document, selectionOffset, selectionLength);
	if (keys == null || keys.size() == 0)
		return false;
	if (resultingCollections == null)
		return true;

	for (Iterator<String> iterator= keys.iterator(); iterator.hasNext();) {
		String key= iterator.next();
		IField field= accessorClass.getField(key);
		if (field.exists())
			fields.add(key);
	}

	ICompilationUnit cu= accessorClass.getCompilationUnit();
	try {
		Change propertiesFileChange= NLSPropertyFileModifier.removeKeys(file.getFullPath(), keys);
		Change[] changes;
		if (fields.size() > 0) {
			Change accessorChange= AccessorClassModifier.removeFields(cu, fields);
			changes= new Change[] { propertiesFileChange, accessorChange };
		} else {
			changes= new Change[] { propertiesFileChange };
		}

		String name= (keys.size() == 1)
				? PropertiesFileEditorMessages.PropertiesCorrectionProcessor_remove_property_label
				: PropertiesFileEditorMessages.PropertiesCorrectionProcessor_remove_properties_label;
		resultingCollections.add(new RemovePropertiesProposal(name, 4, JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE), changes));
	} catch (CoreException e) {
		JavaPlugin.log(e);
		return false;
	}
	return true;
}