org.eclipse.jdt.core.IField Java Examples

The following examples show how to use org.eclipse.jdt.core.IField. 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: 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 #2
Source File: SuperTypeRefactoringProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Computes the compilation units of fields referencing the specified type
 * occurrences.
 *
 * @param units
 *            the compilation unit map (element type:
 *            <code>&lt;IJavaProject, Set&lt;ICompilationUnit&gt;&gt;</code>)
 * @param nodes
 *            the ast nodes representing the type occurrences
 * @throws JavaModelException
 *             if an error occurs
 */
protected final void getFieldReferencingCompilationUnits(final Map<IJavaProject, Set<ICompilationUnit>> units, final ASTNode[] nodes) throws JavaModelException {
	ASTNode node= null;
	IField field= null;
	IJavaProject project= null;
	for (int index= 0; index < nodes.length; index++) {
		node= nodes[index];
		project= RefactoringASTParser.getCompilationUnit(node).getJavaProject();
		if (project != null) {
			final List<IField> fields= getReferencingFields(node, project);
			for (int offset= 0; offset < fields.size(); offset++) {
				field= fields.get(offset);
				Set<ICompilationUnit> set= units.get(project);
				if (set == null) {
					set= new HashSet<ICompilationUnit>();
					units.put(project, set);
				}
				final ICompilationUnit unit= field.getCompilationUnit();
				if (unit != null)
					set.add(unit);
			}
		}
	}
}
 
Example #3
Source File: JDTUtils.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Returns the constant value for the given field.
 *
 * @param field
 *            the field
 * @param typeRoot
 *            the editor input element
 * @param region
 *            the hover region in the editor
 * @return the constant value for the given field or <code>null</code> if none
 *
 */
public static String getConstantValue(IField field, ITypeRoot typeRoot, IRegion region) {
	if (field == null || !isStaticFinal(field)) {
		return null;
	}

	Object constantValue;
	ASTNode node = getHoveredASTNode(typeRoot, region);
	if (node != null) {
		constantValue = getVariableBindingConstValue(node, field);
	} else {
		constantValue = computeFieldConstantFromTypeAST(field, null);
	}
	if (constantValue == null) {
		return null;
	}

	if (constantValue instanceof String) {
		return ASTNodes.getEscapedStringLiteral((String) constantValue);
	} else if (constantValue instanceof Character) {
		return '\'' + constantValue.toString() + '\'';
	} else {
		return constantValue.toString(); // getHexConstantValue(constantValue);
	}
}
 
Example #4
Source File: JdtFindReferencesTest.java    From xtext-xtend with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void testFieldJavaElements() {
  try {
    StringConcatenation _builder = new StringConcatenation();
    _builder.append("class Xtend {");
    _builder.newLine();
    _builder.append("\t");
    _builder.append("int foo");
    _builder.newLine();
    _builder.append("}");
    _builder.newLine();
    final XtendMember field = IterableExtensions.<XtendMember>head(IterableExtensions.<XtendClass>head(Iterables.<XtendClass>filter(this._workbenchTestHelper.xtendFile("Xtend.xtend", _builder.toString()).getXtendTypes(), XtendClass.class)).getMembers());
    IResourcesSetupUtil.waitForBuild();
    Iterable<IJavaElement> _javaElements = this._jvmModelFindReferenceHandler.getJavaElements(field);
    final Procedure1<Iterable<IJavaElement>> _function = (Iterable<IJavaElement> it) -> {
      Assert.assertEquals(1, IterableExtensions.size(it));
      final Function1<IJavaElement, Boolean> _function_1 = (IJavaElement it_1) -> {
        return Boolean.valueOf(((it_1 instanceof IField) && Objects.equal(((IField) it_1).getElementName(), "foo")));
      };
      Assert.assertTrue(IterableExtensions.<IJavaElement>exists(it, _function_1));
    };
    ObjectExtensions.<Iterable<IJavaElement>>operator_doubleArrow(_javaElements, _function);
  } catch (Throwable _e) {
    throw Exceptions.sneakyThrow(_e);
  }
}
 
Example #5
Source File: AddDelegateMethodsAction.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
AddDelegateMethodsContentProvider(CompilationUnit astRoot, IType type, IField[] fields) throws JavaModelException {

			final ITypeBinding binding= ASTNodes.getTypeBinding(astRoot, type);
			if (binding != null) {
				fDelegateEntries= StubUtility2.getDelegatableMethods(binding);

				List<IVariableBinding> expanded= new ArrayList<IVariableBinding>();
				for (int index= 0; index < fields.length; index++) {
					VariableDeclarationFragment fragment= ASTNodeSearchUtil.getFieldDeclarationFragmentNode(fields[index], astRoot);
					if (fragment != null) {
						IVariableBinding variableBinding= fragment.resolveBinding();
						if (variableBinding != null)
							expanded.add(variableBinding);
					}
				}
				fExpanded= expanded.toArray(new IVariableBinding[expanded.size()]);
			}
		}
 
Example #6
Source File: DeltaConverter.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * We don't include nested types because structural changes of nested types should not affect Xtend classes which
 * use top level types.
 * 
 * @deprecated This method is not used anymore.
 */
@Deprecated
protected void traverseType(IType type, NameBasedEObjectDescriptionBuilder acceptor) {
	try {
		if (type.exists()) {
			for (IField field : type.getFields()) {
				if (!Flags.isSynthetic(field.getFlags())) {
					String fieldName = field.getElementName();
					acceptor.accept(fieldName);
				}
			}
			for (IMethod method : type.getMethods()) {
				if (!Flags.isSynthetic(method.getFlags())) {
					String methodName = method.getElementName();
					acceptor.accept(methodName);
				}
			}

		}
	} catch (JavaModelException e) {
		if (LOGGER.isDebugEnabled())
			LOGGER.debug(e, e);
	}
}
 
Example #7
Source File: GenerateGetterAndSetterTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * No setter for final fields (if skipped by user, as per parameter)
 *
 * @throws Exception
 */
@Test
public void test1() throws Exception {
	IField field1 = fClassA.createField("final String field1 = null;", null, false, new NullProgressMonitor());
	runAndApplyOperation(fClassA);

	/* @formatter:off */
	String expected= "public class A {\r\n" +
					"\r\n" +
					"	final String field1 = null;\r\n" +
					"\r\n" +
					"	/**\r\n" +
					"	 * @return Returns the field1.\r\n" +
					"	 */\r\n" +
					"	public String getField1() {\r\n" +
					"		return field1;\r\n" +
					"	}\r\n" +
					"}";
	/* @formatter:on */

	compareSource(expected, fClassA.getSource());
}
 
Example #8
Source File: AddGetterSetterAction.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private static IField[] getGetterFields(Object[] result, Set<IField> set) {
	List<IField> list= new ArrayList<IField>(0);
	Object each= null;
	GetterSetterEntry entry= null;
	for (int i= 0; i < result.length; i++) {
		each= result[i];
		if ((each instanceof GetterSetterEntry)) {
			entry= (GetterSetterEntry) each;
			if (entry.isGetter) {
				list.add(entry.field);
			}
		}
	}
	list= reorderFields(list, set);
	return list.toArray(new IField[list.size()]);
}
 
Example #9
Source File: PushDownRefactoringProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private RefactoringStatus checkAccessedFields(IType[] subclasses, IProgressMonitor pm) throws JavaModelException {
	RefactoringStatus result= new RefactoringStatus();
	IMember[] membersToPushDown= MemberActionInfo.getMembers(getInfosForMembersToBeCreatedInSubclassesOfDeclaringClass());
	List<IMember> pushedDownList= Arrays.asList(membersToPushDown);
	IField[] accessedFields= ReferenceFinderUtil.getFieldsReferencedIn(membersToPushDown, pm);
	for (int i= 0; i < subclasses.length; i++) {
		IType targetClass= subclasses[i];
		ITypeHierarchy targetSupertypes= targetClass.newSupertypeHierarchy(null);
		for (int j= 0; j < accessedFields.length; j++) {
			IField field= accessedFields[j];
			boolean isAccessible= pushedDownList.contains(field) || canBeAccessedFrom(field, targetClass, targetSupertypes) || Flags.isEnum(field.getFlags());
			if (!isAccessible) {
				String message= Messages.format(RefactoringCoreMessages.PushDownRefactoring_field_not_accessible, new String[] { JavaElementLabels.getTextLabel(field, JavaElementLabels.ALL_FULLY_QUALIFIED), JavaElementLabels.getTextLabel(targetClass, JavaElementLabels.ALL_FULLY_QUALIFIED) });
				result.addError(message, JavaStatusContext.create(field));
			}
		}
	}
	pm.done();
	return result;
}
 
Example #10
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 #11
Source File: AddGetterSetterAction.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private static IField[] getGetterSetterFields(Object[] result, Set<IField> set) {
	List<IField> list= new ArrayList<IField>(0);
	Object each= null;
	GetterSetterEntry entry= null;
	boolean getterSet= false;
	for (int i= 0; i < result.length; i++) {
		each= result[i];
		if ((each instanceof GetterSetterEntry)) {
			entry= (GetterSetterEntry) each;
			if (entry.isGetter) {
				getterSet= true;
			}
			if ((!entry.isGetter) && (getterSet == true)) {
				list.add(entry.field);
				getterSet= false;
			}
		} else
			getterSet= false;
	}
	list= reorderFields(list, set);
	return list.toArray(new IField[list.size()]);
}
 
Example #12
Source File: AddGetterSetterOperation.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Generates a new getter method for the specified field
 *
 * @param field the field
 * @param rewrite the list rewrite to use
 * @throws CoreException if an error occurs
 * @throws OperationCanceledException if the operation has been cancelled
 */
private void generateGetterMethod(final IField field, final ListRewrite rewrite) throws CoreException, OperationCanceledException {
	final IType type= field.getDeclaringType();
	final String name= GetterSetterUtil.getGetterName(field, null);
	final IMethod existing= JavaModelUtil.findMethod(name, EMPTY_STRINGS, false, type);
	if (existing == null || !querySkipExistingMethods(existing)) {
		IJavaElement sibling= null;
		if (existing != null) {
			sibling= StubUtility.findNextSibling(existing);
			removeExistingAccessor(existing, rewrite);
		} else
			sibling= fInsert;
		ASTNode insertion= StubUtility2.getNodeToInsertBefore(rewrite, sibling);
		addNewAccessor(type, field, GetterSetterUtil.getGetterStub(field, name, fSettings.createComments, fVisibility | (field.getFlags() & Flags.AccStatic)), rewrite, insertion);
	}
}
 
Example #13
Source File: CommonsLangToStringMethodContent.java    From jenerate with Eclipse Public License 1.0 6 votes vote down vote up
private static String createToStringBuilderString(ToStringGenerationData data) throws JavaModelException {
    StringBuffer content = new StringBuffer();
    CommonsLangToStringStyle toStringStyle = data.getToStringStyle();
    if (CommonsLangToStringStyle.NO_STYLE.equals(toStringStyle)) {
        content.append("new ToStringBuilder(this)");
    } else {
        content.append("new ToStringBuilder(this, ");
        content.append(toStringStyle.getFullStyle());
        content.append(")");
    }
    if (data.appendSuper()) {
        content.append(".appendSuper(super.toString())");
    }
    IField[] checkedFields = data.getCheckedFields();
    for (int i = 0; i < checkedFields.length; i++) {
        content.append(".append(\"");
        content.append(checkedFields[i].getElementName());
        content.append("\", ");
        content.append(MethodContentGenerations.getFieldAccessorString(checkedFields[i],
                data.useGettersInsteadOfFields()));
        content.append(")");
    }
    content.append(".toString();\n");

    return content.toString();
}
 
Example #14
Source File: NLSAccessorFieldRenameParticipant.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private static boolean isPotentialNLSAccessor(ICompilationUnit unit) throws JavaModelException {
	IType type= unit.getTypes()[0];
	if (!type.exists())
		return false;

	IField bundleNameField= getBundleNameField(type.getFields());
	if (bundleNameField == null)
		return false;

	if (!importsOSGIUtil(unit))
		return false;

	IInitializer[] initializers= type.getInitializers();
	for (int i= 0; i < initializers.length; i++) {
		if (Modifier.isStatic(initializers[0].getFlags()))
			return true;
	}

	return false;
}
 
Example #15
Source File: MoveStaticMembersProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private boolean canMoveToInterface(IMember member, boolean is18OrHigher) throws JavaModelException {
	int flags= member.getFlags();
	switch (member.getElementType()) {
		case IJavaElement.FIELD:
			if (!(Flags.isStatic(flags) && Flags.isFinal(flags)))
				return false;
			if (Flags.isEnum(flags))
				return false;
			VariableDeclarationFragment declaration= ASTNodeSearchUtil.getFieldDeclarationFragmentNode((IField) member, fSource.getRoot());
			if (declaration != null)
				return declaration.getInitializer() != null;
			return false;
		case IJavaElement.TYPE: {
			IType type= (IType) member;
			if (type.isInterface() && !Checks.isTopLevel(type))
				return true;
			return Flags.isStatic(flags);
		}
		case IJavaElement.METHOD: {
			return is18OrHigher && Flags.isStatic(flags);
		}
		default:
			return false;
	}
}
 
Example #16
Source File: CommonsLangEqualsMethodContent.java    From jenerate with Eclipse Public License 1.0 6 votes vote down vote up
private String createEqualsMethodContent(EqualsHashCodeGenerationData data, IType objectClass)
        throws JavaModelException {
    StringBuffer content = new StringBuffer();
    String elementName = objectClass.getElementName();
    content.append(MethodContentGenerations.createEqualsContentPrefix(data, objectClass));
    content.append(elementName);
    content.append(" castOther = (");
    content.append(elementName);
    content.append(") other;\n");
    content.append("return new EqualsBuilder()");
    if (data.appendSuper()) {
        content.append(".appendSuper(super.equals(other))");
    }
    IField[] checkedFields = data.getCheckedFields();
    for (int i = 0; i < checkedFields.length; i++) {
        content.append(".append(");
        String fieldName = MethodContentGenerations.getFieldAccessorString(checkedFields[i],
                data.useGettersInsteadOfFields());
        content.append(fieldName);
        content.append(", castOther.");
        content.append(fieldName);
        content.append(")");
    }
    content.append(".isEquals();\n");
    return content.toString();
}
 
Example #17
Source File: HierarchyProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
protected static FieldDeclaration createNewFieldDeclarationNode(final ASTRewrite rewrite, final CompilationUnit unit, final IField field, final VariableDeclarationFragment oldFieldFragment, final TypeVariableMaplet[] mapping, final IProgressMonitor monitor, final RefactoringStatus status, final int modifiers) throws JavaModelException {
	final VariableDeclarationFragment newFragment= rewrite.getAST().newVariableDeclarationFragment();
	copyExtraDimensions(oldFieldFragment, newFragment);
	if (oldFieldFragment.getInitializer() != null) {
		Expression newInitializer= null;
		if (mapping.length > 0)
			newInitializer= createPlaceholderForExpression(oldFieldFragment.getInitializer(), field.getCompilationUnit(), mapping, rewrite);
		else
			newInitializer= createPlaceholderForExpression(oldFieldFragment.getInitializer(), field.getCompilationUnit(), rewrite);
		newFragment.setInitializer(newInitializer);
	}
	newFragment.setName(((SimpleName) ASTNode.copySubtree(rewrite.getAST(), oldFieldFragment.getName())));
	final FieldDeclaration newField= rewrite.getAST().newFieldDeclaration(newFragment);
	final FieldDeclaration oldField= ASTNodeSearchUtil.getFieldDeclarationNode(field, unit);
	copyJavadocNode(rewrite, oldField, newField);
	copyAnnotations(oldField, newField);
	newField.modifiers().addAll(ASTNodeFactory.newModifiers(rewrite.getAST(), modifiers));
	final Type oldType= oldField.getType();
	Type newType= null;
	if (mapping.length > 0) {
		newType= createPlaceholderForType(oldType, field.getCompilationUnit(), mapping, rewrite);
	} else
		newType= createPlaceholderForType(oldType, field.getCompilationUnit(), rewrite);
	newField.setType(newType);
	return newField;
}
 
Example #18
Source File: GenerateGetterAndSetterTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void testWithoutGeneratingComments() throws Exception {
	IField field1 = fClassA.createField("String field1;", null, false, new NullProgressMonitor());
	runAndApplyOperation(fClassA, false);

	/* @formatter:off */
	String expected= "public class A {\r\n" +
					"\r\n" +
					"	String field1;\r\n" +
					"\r\n" +
					"	public String getField1() {\r\n" +
					"		return field1;\r\n" +
					"	}\r\n" +
					"\r\n" +
					"	public void setField1(String field1) {\r\n" +
					"		this.field1 = field1;\r\n" +
					"	}\r\n" +
					"}";
	/* @formatter:on */

	compareSource(expected, fClassA.getSource());
}
 
Example #19
Source File: GroovyUtil.java    From bonita-studio with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Helper method to retrieve the constant field of Custom Groovy Type
 *
 * @param className
 * @return list of String (the values)
 */
public static List<String> getTypeValues(final String className) {

    final List<String> result = new ArrayList<>();
    try {
        final IType t = getType(className);
        if (t == null) {
            return result;
        }
        for (final IField f : t.getFields()) {
            final String fieldSource = f.getSource();
            if (fieldSource != null
                    && fieldSource.indexOf(GROOVY_CONSTANT_SEPARATOR) != -1) {
                result.add(fieldSource.substring(
                        fieldSource.indexOf(GROOVY_CONSTANT_SEPARATOR) + 1,
                        fieldSource.lastIndexOf(GROOVY_CONSTANT_SEPARATOR))); // )
            }
        }
    } catch (final Exception e) {
        BonitaStudioLog.error(e);
    }
    return result;
}
 
Example #20
Source File: JavaDeleteProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private List<IMethod> getGettersSettersToDelete(Map<IField, IMethod[]> getterSetterMapping) {
	List<IMethod> gettersSettersToAdd= new ArrayList<IMethod>(getterSetterMapping.size());
	String queryTitle= RefactoringCoreMessages.DeleteRefactoring_8;
	IConfirmQuery getterSetterQuery= fDeleteQueries.createYesYesToAllNoNoToAllQuery(queryTitle, true, IReorgQueries.CONFIRM_DELETE_GETTER_SETTER);
	for (Iterator<IField> iter= getterSetterMapping.keySet().iterator(); iter.hasNext();) {
		IField field= iter.next();
		Assert.isTrue(hasGetter(getterSetterMapping, field) || hasSetter(getterSetterMapping, field));
		String deleteGetterSetter= Messages.format(RefactoringCoreMessages.DeleteRefactoring_9, JavaElementUtil.createFieldSignature(field));
		if (getterSetterQuery.confirm(deleteGetterSetter)){
			if (hasGetter(getterSetterMapping, field))
				gettersSettersToAdd.add(getGetter(getterSetterMapping, field));
			if (hasSetter(getterSetterMapping, field))
				gettersSettersToAdd.add(getSetter(getterSetterMapping, field));
		}
	}
	return gettersSettersToAdd;
}
 
Example #21
Source File: JavaDeleteProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private void removeAlreadySelectedMethods(Map<IField, IMethod[]> getterSetterMapping) {
	List<IJavaElement> elementsToDelete= Arrays.asList(fJavaElements);
	for (Iterator<IField> iter= getterSetterMapping.keySet().iterator(); iter.hasNext();) {
		IField field= iter.next();
		//remove getter
		IMethod getter= getGetter(getterSetterMapping, field);
		if (getter != null && elementsToDelete.contains(getter))
			removeGetterFromMapping(getterSetterMapping, field);

		//remove setter
		IMethod setter= getSetter(getterSetterMapping, field);
		if (setter != null && elementsToDelete.contains(setter))
			removeSetterFromMapping(getterSetterMapping, field);

		//both getter and setter already included
		if (! hasGetter(getterSetterMapping, field) && ! hasSetter(getterSetterMapping, field))
			iter.remove();
	}
}
 
Example #22
Source File: GenerateGetterSetterOperation.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
public static AccessorField[] getUnimplementedAccessors(IType type) throws JavaModelException {
	if (!supportsGetterSetter(type)) {
		return new AccessorField[0];
	}

	List<AccessorField> unimplemented = new ArrayList<>();
	IField[] fields = type.getFields();
	for (IField field : fields) {
		int flags = field.getFlags();
		if (!Flags.isEnum(flags)) {
			boolean isStatic = Flags.isStatic(flags);
			boolean generateGetter = (GetterSetterUtil.getGetter(field) == null);
			boolean generateSetter = (!Flags.isFinal(flags) && GetterSetterUtil.getSetter(field) == null);
			if (generateGetter || generateSetter) {
				unimplemented.add(new AccessorField(field.getElementName(), isStatic, generateGetter, generateSetter));
			}
		}
	}

	return unimplemented.toArray(new AccessorField[0]);
}
 
Example #23
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 #24
Source File: SelfEncapsulateFieldRefactoring.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Creates a new self encapsulate field refactoring.
 *
 * @param field
 *            the field, or <code>null</code> if invoked by scripting
 * @throws JavaModelException
 *             if initialization failed
 */
public SelfEncapsulateFieldRefactoring(IField field) throws JavaModelException {
	fGenerateJavadoc = true;
	fEncapsulateDeclaringClass = true;
	fChangeManager = new TextChangeManager();
	fField = field;
	if (field != null) {
		initialize(field);
	}
}
 
Example #25
Source File: JavaMatchFilter.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public boolean isApplicable(JavaSearchQuery query) {
	QuerySpecification spec= query.getSpecification();
	if (spec instanceof ElementQuerySpecification) {
		ElementQuerySpecification elementSpec= (ElementQuerySpecification) spec;
		IJavaElement element= elementSpec.getElement();
		return element instanceof IField || element instanceof ILocalVariable;
	} else if (spec instanceof PatternQuerySpecification) {
		PatternQuerySpecification patternSpec= (PatternQuerySpecification) spec;
		return patternSpec.getSearchFor() == IJavaSearchConstants.FIELD;
	}
	return false;
}
 
Example #26
Source File: RefactoringAvailabilityTester.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
public static boolean isConvertAnonymousAvailable(final IType type) throws JavaModelException {
	if (Checks.isAvailable(type)) {
		final IJavaElement element = type.getParent();
		if (element instanceof IField && JdtFlags.isEnum((IMember) element)) {
			return false;
		}
		return type.isAnonymous();
	}
	return false;
}
 
Example #27
Source File: PotentialProgrammingProblemsFix.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private void addTypes(IType[] allSubtypes, HashSet<ICompilationUnit> cus, List<IType> types) throws JavaModelException {
	for (int i= 0; i < allSubtypes.length; i++) {
		IType type= allSubtypes[i];

		IField field= type.getField(NAME_FIELD);
		if (!field.exists()) {
			if (type.isClass() && cus.contains(type.getCompilationUnit())){
				types.add(type);
			}
		}
	}
}
 
Example #28
Source File: StubCreator.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
protected void appendEnumConstants(final IType type) throws JavaModelException {
	final IField[] fields= type.getFields();
	final List<IField> list= new ArrayList<IField>(fields.length);
	for (int index= 0; index < fields.length; index++) {
		final IField field= fields[index];
		if (Flags.isEnum(field.getFlags()))
			list.add(field);
	}
	for (int index= 0; index < list.size(); index++) {
		if (index > 0)
			fBuffer.append(","); //$NON-NLS-1$
		fBuffer.append(list.get(index).getElementName());
	}
	fBuffer.append(";"); //$NON-NLS-1$
}
 
Example #29
Source File: MemberCheckUtil.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public static RefactoringStatus checkMembersInDestinationType(IMember[] members, IType destinationType) throws JavaModelException {
	RefactoringStatus result= new RefactoringStatus();
	for (int i= 0; i < members.length; i++) {
		if (members[i].getElementType() == IJavaElement.METHOD)
			checkMethodInType(destinationType, result, (IMethod)members[i]);
		else if (members[i].getElementType() == IJavaElement.FIELD)
			checkFieldInType(destinationType, result, (IField)members[i]);
		else if (members[i].getElementType() == IJavaElement.TYPE)
			checkTypeInType(destinationType, result, (IType)members[i]);
	}
	return result;
}
 
Example #30
Source File: JavaRefactoringIntegrationTest.java    From xtext-xtend with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testRenameJavaField() throws Exception {
	createFile("JavaClass.java", "public class JavaClass { protected int foo; }");
	String xtendModel = "class XtendClass extends JavaClass { int bar = foo }";
	IFile xtendClass = createFile("XtendClass.xtend", xtendModel);
	IField javaField = findJavaType("JavaClass").getField("foo");
	assertNotNull(javaField);
	renameJavaElement(javaField, "baz");
	fileAsserts.assertFileContains(xtendClass, "int bar = baz");
}