org.eclipse.jdt.core.dom.Modifier Java Examples

The following examples show how to use org.eclipse.jdt.core.dom.Modifier. 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: MoveInnerToTopRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public boolean visit(final ClassInstanceCreation node) {
	Assert.isNotNull(node);
	if (fCreateInstanceField) {
		final AST ast= node.getAST();
		final Type type= node.getType();
		final ITypeBinding binding= type.resolveBinding();
		if (binding != null && binding.getDeclaringClass() != null && !Bindings.equals(binding, fTypeBinding) && fSourceRewrite.getRoot().findDeclaringNode(binding) != null) {
			if (!Modifier.isStatic(binding.getModifiers())) {
				Expression expression= null;
				if (fCodeGenerationSettings.useKeywordThis || fEnclosingInstanceFieldName.equals(fNameForEnclosingInstanceConstructorParameter)) {
					final FieldAccess access= ast.newFieldAccess();
					access.setExpression(ast.newThisExpression());
					access.setName(ast.newSimpleName(fEnclosingInstanceFieldName));
					expression= access;
				} else
					expression= ast.newSimpleName(fEnclosingInstanceFieldName);
				if (node.getExpression() != null)
					fSourceRewrite.getImportRemover().registerRemovedNode(node.getExpression());
				fSourceRewrite.getASTRewrite().set(node, ClassInstanceCreation.EXPRESSION_PROPERTY, expression, fGroup);
			} else
				addTypeQualification(type, fSourceRewrite, fGroup);
		}
	}
	return true;
}
 
Example #2
Source File: GenerateHashCodeEqualsAction.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
@Override
boolean generateCandidates() {
	IVariableBinding[] fCandidateFields= fTypeBinding.getDeclaredFields();

	allFields= new ArrayList<IVariableBinding>();
	selectedFields= new ArrayList<IVariableBinding>();
	for (int i= 0; i < fCandidateFields.length; i++) {
		if (!Modifier.isStatic(fCandidateFields[i].getModifiers())) {
			allFields.add(fCandidateFields[i]);
			if (!Modifier.isTransient(fCandidateFields[i].getModifiers()))
				selectedFields.add(fCandidateFields[i]);
		}
	}
	if (allFields.isEmpty()) {
		return false;
	}
	return true;
}
 
Example #3
Source File: JavaStatementPostfixContext.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Adds a new field to the {@link AST} using the given type and variable name. The method
 * returns a {@link TextEdit} which can then be applied using the {@link #applyTextEdit(TextEdit)} method.
 * 
 * @param type
 * @param varName
 * @return a {@link TextEdit} which represents the changes which would be made, or <code>null</code> if the field
 * can not be created.
 */
public TextEdit addField(String type, String varName, boolean publicField, boolean staticField, boolean finalField, String value) {
	
	if (isReadOnly())
		return null;

	if (!domInitialized)
		initDomAST();
	
	boolean isStatic = isBodyStatic();
	int modifiers = (!publicField) ? Modifier.PRIVATE : Modifier.PUBLIC;
	if (isStatic || staticField) {
		modifiers |= Modifier.STATIC;
	}
	if (finalField) {
		modifiers |= Modifier.FINAL;
	}
	
	ASTRewrite rewrite= ASTRewrite.create(parentDeclaration.getAST());
	
	VariableDeclarationFragment newDeclFrag = addFieldDeclaration(rewrite, parentDeclaration, modifiers, varName, type, value);

	TextEdit te = rewrite.rewriteAST(getDocument(), null);
	return te;
}
 
Example #4
Source File: ASTResolving.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private static boolean isVariableDefinedInContext(IBinding binding, ITypeBinding typeVariable) {
	if (binding.getKind() == IBinding.VARIABLE) {
		IVariableBinding var= (IVariableBinding) binding;
		binding= var.getDeclaringMethod();
		if (binding == null) {
			binding= var.getDeclaringClass();
		}
	}
	if (binding instanceof IMethodBinding) {
		if (binding == typeVariable.getDeclaringMethod()) {
			return true;
		}
		binding= ((IMethodBinding) binding).getDeclaringClass();
	}

	while (binding instanceof ITypeBinding) {
		if (binding == typeVariable.getDeclaringClass()) {
			return true;
		}
		if (Modifier.isStatic(binding.getModifiers())) {
			break;
		}
		binding= ((ITypeBinding) binding).getDeclaringClass();
	}
	return false;
}
 
Example #5
Source File: InJavaImporter.java    From jdt2famix with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * We pass both the fragment and the field because we need the field type when
 * the binding cannot be resolved
 */
public Attribute ensureAttributeForFragment(VariableDeclarationFragment fragment, FieldDeclaration field) {
	IVariableBinding binding = fragment.resolveBinding();
	Attribute attribute;
	if (binding == null)
		attribute = ensureAttributeFromFragmentIntoParentType(fragment, field,
				this.topFromContainerStack(Type.class));
	else {
		attribute = ensureAttributeForVariableBinding(binding);
		extractBasicModifiersFromBinding(binding.getModifiers(), attribute);
		if (Modifier.isStatic(binding.getModifiers()))
			attribute.setHasClassScope(true);
	}
	attribute.setIsStub(true);
	return attribute;
}
 
Example #6
Source File: InferTypeArgumentsTCModel.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
public VariableVariable2 makeVariableVariable(IVariableBinding variableBinding) {
	if (variableBinding == null)
		return null;
	TType type= getBoxedType(variableBinding.getType(), /*no boxing*/null);
	if (type == null)
		return null;
	VariableVariable2 cv= new VariableVariable2(type, variableBinding);
	VariableVariable2 storedCv= (VariableVariable2) storedCv(cv);
	if (storedCv == cv) {
		if (! variableBinding.isField() || Modifier.isPrivate(variableBinding.getModifiers()))
			fCuScopedConstraintVariables.add(storedCv);
		makeElementVariables(storedCv, type);
		makeArrayElementVariable(storedCv);
		if (fStoreToString)
			storedCv.setData(ConstraintVariable2.TO_STRING, '[' + variableBinding.getName() + ']');
	}
	return storedCv;
}
 
Example #7
Source File: UiBinderJavaProblem.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
public static Set<UiBinderJavaProblem> createPrivateUiField(
    FieldDeclaration uiFieldDecl, Modifier privateModifier) {
  Set<UiBinderJavaProblem> problems = new HashSet<UiBinderJavaProblem>();

  List<VariableDeclarationFragment> varDecls = uiFieldDecl.fragments();
  for (VariableDeclarationFragment varDecl : varDecls) {
    String fieldName = varDecl.getName().getIdentifier();

    UiBinderJavaProblem problem = create(privateModifier,
        UiBinderJavaProblemType.PRIVATE_UI_FIELD, new String[] {fieldName},
        NO_STRINGS);
    if (problem != null) {
      problems.add(problem);
    }
  }

  return problems;
}
 
Example #8
Source File: FindBrokenNLSKeysAction.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)) { //new school
		IInitializer[] initializers= type.getInitializers();
		for (int i= 0; i < initializers.length; i++) {
			if (Modifier.isStatic(initializers[0].getFlags()))
				return true;
		}
	} else { //old school
		IMethod[] methods= type.getMethods();
		for (int i= 0; i < methods.length; i++) {
			IMethod method= methods[i];
			if (isValueAccessor(method))
				return true;
		}
	}

	return false;
}
 
Example #9
Source File: MoveMethodRefactoring.java    From JDeodorant with MIT License 6 votes vote down vote up
private void modifySourceStaticMethodInvocationsInTargetClass(MethodDeclaration newMethodDeclaration, ASTRewrite targetRewriter) {
	ExpressionExtractor extractor = new ExpressionExtractor();	
	List<Expression> sourceMethodInvocations = extractor.getMethodInvocations(sourceMethod.getBody());
	List<Expression> newMethodInvocations = extractor.getMethodInvocations(newMethodDeclaration.getBody());
	int i = 0;
	for(Expression expression : sourceMethodInvocations) {
		if(expression instanceof MethodInvocation) {
			MethodInvocation methodInvocation = (MethodInvocation)expression;
			IMethodBinding methodBinding = methodInvocation.resolveMethodBinding();
			if((methodBinding.getModifiers() & Modifier.STATIC) != 0 &&
					methodBinding.getDeclaringClass().isEqualTo(sourceTypeDeclaration.resolveBinding()) &&
					!additionalMethodsToBeMoved.containsKey(methodInvocation)) {
				AST ast = newMethodDeclaration.getAST();
				SimpleName qualifier = ast.newSimpleName(sourceTypeDeclaration.getName().getIdentifier());
				targetRewriter.set(newMethodInvocations.get(i), MethodInvocation.EXPRESSION_PROPERTY, qualifier, null);
				this.additionalTypeBindingsToBeImportedInTargetClass.add(sourceTypeDeclaration.resolveBinding());
			}
		}
		i++;
	}
}
 
Example #10
Source File: ReplaceTypeCodeWithStateStrategy.java    From JDeodorant with MIT License 6 votes vote down vote up
private void createStateField() {
	ASTRewrite sourceRewriter = ASTRewrite.create(sourceTypeDeclaration.getAST());
	AST contextAST = sourceTypeDeclaration.getAST();
	ListRewrite contextBodyRewrite = sourceRewriter.getListRewrite(sourceTypeDeclaration, TypeDeclaration.BODY_DECLARATIONS_PROPERTY);
	VariableDeclarationFragment typeFragment = createStateFieldVariableDeclarationFragment(sourceRewriter, contextAST);
	
	FieldDeclaration typeFieldDeclaration = contextAST.newFieldDeclaration(typeFragment);
	sourceRewriter.set(typeFieldDeclaration, FieldDeclaration.TYPE_PROPERTY, contextAST.newSimpleName(abstractClassName), null);
	ListRewrite typeFieldDeclarationModifiersRewrite = sourceRewriter.getListRewrite(typeFieldDeclaration, FieldDeclaration.MODIFIERS2_PROPERTY);
	typeFieldDeclarationModifiersRewrite.insertLast(contextAST.newModifier(Modifier.ModifierKeyword.PRIVATE_KEYWORD), null);
	contextBodyRewrite.insertBefore(typeFieldDeclaration, typeCheckElimination.getTypeField().getParent(), null);
	
	try {
		TextEdit sourceEdit = sourceRewriter.rewriteAST();
		ICompilationUnit sourceICompilationUnit = (ICompilationUnit)sourceCompilationUnit.getJavaElement();
		CompilationUnitChange change = compilationUnitChanges.get(sourceICompilationUnit);
		change.getEdit().addChild(sourceEdit);
		change.addTextEditGroup(new TextEditGroup("Create field holding the current state", new TextEdit[] {sourceEdit}));
	} catch (JavaModelException e) {
		e.printStackTrace();
	}
}
 
Example #11
Source File: ReplaceInvocationsRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public Change createChange(IProgressMonitor pm) throws CoreException {
	// TODO: update for fSelectionStart == -1
	final Map<String, String> arguments= new HashMap<String, String>();
	String project= null;
	IJavaProject javaProject= fSelectionTypeRoot.getJavaProject();
	if (javaProject != null)
		project= javaProject.getElementName();
	final IMethodBinding binding= fSourceProvider.getDeclaration().resolveBinding();
	int flags= RefactoringDescriptor.STRUCTURAL_CHANGE | JavaRefactoringDescriptor.JAR_REFACTORING | JavaRefactoringDescriptor.JAR_SOURCE_ATTACHMENT;
	if (!Modifier.isPrivate(binding.getModifiers()))
		flags|= RefactoringDescriptor.MULTI_CHANGE;
	final String description= Messages.format(RefactoringCoreMessages.ReplaceInvocationsRefactoring_descriptor_description_short, BasicElementLabels.getJavaElementName(binding.getName()));
	final String header= Messages.format(RefactoringCoreMessages.ReplaceInvocationsRefactoring_descriptor_description, new String[] { BindingLabelProvider.getBindingLabel(binding, JavaElementLabels.ALL_FULLY_QUALIFIED), BindingLabelProvider.getBindingLabel(binding.getDeclaringClass(), JavaElementLabels.ALL_FULLY_QUALIFIED)});
	final JDTRefactoringDescriptorComment comment= new JDTRefactoringDescriptorComment(project, this, header);
	comment.addSetting(Messages.format(RefactoringCoreMessages.ReplaceInvocationsRefactoring_original_pattern, BindingLabelProvider.getBindingLabel(binding, JavaElementLabels.ALL_FULLY_QUALIFIED)));
	if (!fTargetProvider.isSingle())
		comment.addSetting(RefactoringCoreMessages.ReplaceInvocationsRefactoring_replace_references);
	final JavaRefactoringDescriptor descriptor= new JavaRefactoringDescriptor(ID_REPLACE_INVOCATIONS, project, description, comment.asString(), arguments, flags){}; //REVIEW Unregistered ID!
	arguments.put(JavaRefactoringDescriptorUtil.ATTRIBUTE_INPUT, JavaRefactoringDescriptorUtil.elementToHandle(project, fSelectionTypeRoot));
	arguments.put(JavaRefactoringDescriptorUtil.ATTRIBUTE_SELECTION, new Integer(fSelectionStart).toString() + " " + new Integer(fSelectionLength).toString()); //$NON-NLS-1$
	arguments.put(ATTRIBUTE_MODE, new Integer(fTargetProvider.isSingle() ? 0 : 1).toString());
	return new DynamicValidationRefactoringChange(descriptor, RefactoringCoreMessages.ReplaceInvocationsRefactoring_change_name, fChangeManager.getAllChanges());
}
 
Example #12
Source File: ModifierCorrectionSubProcessor.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
private static int getNeededVisibility(ASTNode currNode, ITypeBinding targetType, IBinding binding) {
	ITypeBinding currNodeBinding = Bindings.getBindingOfParentType(currNode);
	if (currNodeBinding == null) { // import
		return Modifier.PUBLIC;
	}

	if (Bindings.isSuperType(targetType, currNodeBinding)) {
		if (binding != null && (JdtFlags.isProtected(binding) || binding.getKind() == IBinding.TYPE)) {
			return Modifier.PUBLIC;
		}
		return Modifier.PROTECTED;
	}

	if (currNodeBinding.getPackage().getKey().equals(targetType.getPackage().getKey())) {
		return 0;
	}
	return Modifier.PUBLIC;
}
 
Example #13
Source File: MoveInstanceMethodProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Is the specified name a field access?
 *
 * @param name
 *            the name to check
 * @return <code>true</code> if this name is a field access,
 *         <code>false</code> otherwise
 */
protected static boolean isFieldAccess(final SimpleName name) {
	Assert.isNotNull(name);
	final IBinding binding= name.resolveBinding();
	if (!(binding instanceof IVariableBinding))
		return false;
	final IVariableBinding variable= (IVariableBinding) binding;
	if (!variable.isField())
		return false;
	if ("length".equals(name.getIdentifier())) { //$NON-NLS-1$
		final ASTNode parent= name.getParent();
		if (parent instanceof QualifiedName) {
			final QualifiedName qualified= (QualifiedName) parent;
			final ITypeBinding type= qualified.getQualifier().resolveTypeBinding();
			if (type != null && type.isArray())
				return false;
		}
	}
	return !Modifier.isStatic(variable.getModifiers());
}
 
Example #14
Source File: AccessorClassModifier.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private FieldDeclaration getNewFinalStringFieldDeclaration(String name) {
	VariableDeclarationFragment variableDeclarationFragment= fAst.newVariableDeclarationFragment();
	variableDeclarationFragment.setName(fAst.newSimpleName(name));

	FieldDeclaration fieldDeclaration= fAst.newFieldDeclaration(variableDeclarationFragment);
	fieldDeclaration.setType(fAst.newSimpleType(fAst.newSimpleName("String"))); //$NON-NLS-1$
	fieldDeclaration.modifiers().add(fAst.newModifier(Modifier.ModifierKeyword.PUBLIC_KEYWORD));
	fieldDeclaration.modifiers().add(fAst.newModifier(Modifier.ModifierKeyword.STATIC_KEYWORD));

	return fieldDeclaration;
}
 
Example #15
Source File: JdtFlags.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public static int getVisibilityCode(String visibilityString) {
	Assert.isNotNull(visibilityString);
	if (VISIBILITY_STRING_PACKAGE.equals(visibilityString))
		return 0;
	else if (VISIBILITY_STRING_PRIVATE.equals(visibilityString))
		return Modifier.PRIVATE;
	else if (VISIBILITY_STRING_PROTECTED.equals(visibilityString))
		return Modifier.PROTECTED;
	else if (VISIBILITY_STRING_PUBLIC.equals(visibilityString))
		return Modifier.PUBLIC;
	return VISIBILITY_CODE_INVALID;
}
 
Example #16
Source File: ChangePublicToProtectedResolution.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
private Modifier getPublicModifier(MethodDeclaration method) {
    List<?> list = method.modifiers();
    for (Object o : list) {
        if (o.getClass().equals(Modifier.class)) {
            Modifier mdf = (Modifier) o;
            if (mdf.getKeyword().equals(PUBLIC_KEYWORD)) {
                return mdf;
            }
        }

    }
    return null;
}
 
Example #17
Source File: JdtFlags.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
public static int getVisibilityCode(BodyDeclaration bodyDeclaration) {
	if (isPublic(bodyDeclaration)) {
		return Modifier.PUBLIC;
	} else if (isProtected(bodyDeclaration)) {
		return Modifier.PROTECTED;
	} else if (isPackageVisible(bodyDeclaration)) {
		return Modifier.NONE;
	} else if (isPrivate(bodyDeclaration)) {
		return Modifier.PRIVATE;
	}
	Assert.isTrue(false);
	return VISIBILITY_CODE_INVALID;
}
 
Example #18
Source File: OverrideMethodsOperation.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
private static OverridableMethod convertToSerializableMethod(IMethodBinding binding, boolean unimplemented) {
	OverridableMethod result = new OverridableMethod();
	result.bindingKey = binding.getKey();
	result.name = binding.getName();
	result.parameters = getMethodParameterTypes(binding, false);
	result.unimplemented = unimplemented || Modifier.isAbstract(binding.getModifiers());
	result.declaringClass = binding.getDeclaringClass().getQualifiedName();
	result.declaringClassType = binding.getDeclaringClass().isInterface() ? "interface" : "class";
	return result;
}
 
Example #19
Source File: UnimplementedCodeFix.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public void rewriteAST(CompilationUnitRewrite cuRewrite, LinkedProposalModel linkedProposalPositions) throws CoreException {
	AST ast= cuRewrite.getAST();
	ASTRewrite rewrite= cuRewrite.getASTRewrite();
	Modifier newModifier= ast.newModifier(Modifier.ModifierKeyword.ABSTRACT_KEYWORD);
	TextEditGroup textEditGroup= createTextEditGroup(CorrectionMessages.UnimplementedCodeFix_TextEditGroup_label, cuRewrite);
	rewrite.getListRewrite(fTypeDeclaration, TypeDeclaration.MODIFIERS2_PROPERTY).insertLast(newModifier, textEditGroup);

	LinkedProposalPositionGroup group= new LinkedProposalPositionGroup("modifier"); //$NON-NLS-1$
	group.addPosition(rewrite.track(newModifier), !linkedProposalPositions.hasLinkedPositions());
	linkedProposalPositions.addPositionGroup(group);
}
 
Example #20
Source File: JavaASTFlattener.java    From xtext-xtend with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public boolean visit(final EnumDeclaration node) {
  Javadoc _javadoc = node.getJavadoc();
  boolean _tripleNotEquals = (_javadoc != null);
  if (_tripleNotEquals) {
    node.getJavadoc().accept(this);
  }
  this.appendModifiers(node, node.modifiers());
  boolean _isPackageVisibility = this._aSTFlattenerUtils.isPackageVisibility(Iterables.<Modifier>filter(node.modifiers(), Modifier.class));
  if (_isPackageVisibility) {
    this.appendToBuffer("package ");
  }
  this.appendToBuffer("enum ");
  node.getName().accept(this);
  this.appendSpaceToBuffer();
  boolean _isEmpty = node.superInterfaceTypes().isEmpty();
  boolean _not = (!_isEmpty);
  if (_not) {
    this.addProblem(node, "Enum cannot have a supertype");
    this.appendToBuffer("implements ");
    this.visitAllSeparatedByComma(node.superInterfaceTypes());
    this.appendSpaceToBuffer();
  }
  this.appendToBuffer("{");
  this.increaseIndent();
  this.appendLineWrapToBuffer();
  this.visitAllSeparatedByComma(node.enumConstants());
  boolean _isEmpty_1 = node.bodyDeclarations().isEmpty();
  boolean _not_1 = (!_isEmpty_1);
  if (_not_1) {
    this.addProblem(node, "Enum cannot have any body declaration statements");
    this.appendToBuffer(";");
    this.appendLineWrapToBuffer();
    this.visitAll(node.bodyDeclarations());
  }
  this.decreaseIndent();
  this.appendToBuffer("}");
  return false;
}
 
Example #21
Source File: StubUtility2.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private static void getOverridableMethods(AST ast, ITypeBinding superBinding, List<IMethodBinding> allMethods) {
	IMethodBinding[] methods= superBinding.getDeclaredMethods();
	for (int offset= 0; offset < methods.length; offset++) {
		final int modifiers= methods[offset].getModifiers();
		if (!methods[offset].isConstructor() && !Modifier.isStatic(modifiers) && !Modifier.isPrivate(modifiers)) {
			if (findOverridingMethod(methods[offset], allMethods) == null && !Modifier.isStatic(modifiers))
				allMethods.add(methods[offset]);
		}
	}
	ITypeBinding[] superInterfaces= superBinding.getInterfaces();
	for (int index= 0; index < superInterfaces.length; index++) {
		getOverridableMethods(ast, superInterfaces[index], allMethods);
	}
}
 
Example #22
Source File: ChangeSignatureProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public int[] getAvailableVisibilities() throws JavaModelException{
	if (fTopMethod.getDeclaringType().isInterface())
		return new int[]{Modifier.PUBLIC};
	else if (fTopMethod.getDeclaringType().isEnum() && fTopMethod.isConstructor())
		return new int[]{	Modifier.NONE,
							Modifier.PRIVATE};
	else
		return new int[]{	Modifier.PUBLIC,
							Modifier.PROTECTED,
							Modifier.NONE,
							Modifier.PRIVATE};
}
 
Example #23
Source File: ASTNodes.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private static int getOrderPreference(BodyDeclaration member, MembersOrderPreferenceCache store) {
	int memberType= member.getNodeType();
	int modifiers= member.getModifiers();

	switch (memberType) {
		case ASTNode.TYPE_DECLARATION:
		case ASTNode.ENUM_DECLARATION :
		case ASTNode.ANNOTATION_TYPE_DECLARATION :
			return store.getCategoryIndex(MembersOrderPreferenceCache.TYPE_INDEX) * 2;
		case ASTNode.FIELD_DECLARATION:
			if (Modifier.isStatic(modifiers)) {
				int index= store.getCategoryIndex(MembersOrderPreferenceCache.STATIC_FIELDS_INDEX) * 2;
				if (Modifier.isFinal(modifiers)) {
					return index; // first final static, then static
				}
				return index + 1;
			}
			return store.getCategoryIndex(MembersOrderPreferenceCache.FIELDS_INDEX) * 2;
		case ASTNode.INITIALIZER:
			if (Modifier.isStatic(modifiers)) {
				return store.getCategoryIndex(MembersOrderPreferenceCache.STATIC_INIT_INDEX) * 2;
			}
			return store.getCategoryIndex(MembersOrderPreferenceCache.INIT_INDEX) * 2;
		case ASTNode.ANNOTATION_TYPE_MEMBER_DECLARATION:
			return store.getCategoryIndex(MembersOrderPreferenceCache.METHOD_INDEX) * 2;
		case ASTNode.METHOD_DECLARATION:
			if (Modifier.isStatic(modifiers)) {
				return store.getCategoryIndex(MembersOrderPreferenceCache.STATIC_METHODS_INDEX) * 2;
			}
			if (((MethodDeclaration) member).isConstructor()) {
				return store.getCategoryIndex(MembersOrderPreferenceCache.CONSTRUCTORS_INDEX) * 2;
			}
			return store.getCategoryIndex(MembersOrderPreferenceCache.METHOD_INDEX) * 2;
		default:
			return 100;
	}
}
 
Example #24
Source File: GenericModifierPredicate.java    From SparkBuilderGenerator with MIT License 5 votes vote down vote up
public boolean test(BodyDeclaration method, Predicate<IExtendedModifier> modifiedPredicate) {
    return ((List<IExtendedModifier>) method.modifiers())
            .stream()
            .filter(modifier -> modifier instanceof Modifier)
            .filter(modifiedPredicate)
            .findFirst()
            .isPresent();
}
 
Example #25
Source File: UMLModelASTReader.java    From RefactoringMiner with MIT License 5 votes vote down vote up
private List<UMLAttribute> processFieldDeclaration(CompilationUnit cu, FieldDeclaration fieldDeclaration, boolean isInterfaceField, String sourceFile) {
	UMLJavadoc javadoc = generateJavadoc(fieldDeclaration);
	List<UMLAttribute> attributes = new ArrayList<UMLAttribute>();
	Type fieldType = fieldDeclaration.getType();
	List<VariableDeclarationFragment> fragments = fieldDeclaration.fragments();
	for(VariableDeclarationFragment fragment : fragments) {
		UMLType type = UMLType.extractTypeObject(cu, sourceFile, fieldType, fragment.getExtraDimensions());
		String fieldName = fragment.getName().getFullyQualifiedName();
		LocationInfo locationInfo = generateLocationInfo(cu, sourceFile, fragment, CodeElementType.FIELD_DECLARATION);
		UMLAttribute umlAttribute = new UMLAttribute(fieldName, type, locationInfo);
		VariableDeclaration variableDeclaration = new VariableDeclaration(cu, sourceFile, fragment);
		variableDeclaration.setAttribute(true);
		umlAttribute.setVariableDeclaration(variableDeclaration);
		umlAttribute.setJavadoc(javadoc);
		
		int fieldModifiers = fieldDeclaration.getModifiers();
		if((fieldModifiers & Modifier.PUBLIC) != 0)
			umlAttribute.setVisibility("public");
		else if((fieldModifiers & Modifier.PROTECTED) != 0)
			umlAttribute.setVisibility("protected");
		else if((fieldModifiers & Modifier.PRIVATE) != 0)
			umlAttribute.setVisibility("private");
		else if(isInterfaceField)
			umlAttribute.setVisibility("public");
		else
			umlAttribute.setVisibility("package");
		
		if((fieldModifiers & Modifier.FINAL) != 0)
			umlAttribute.setFinal(true);
		
		if((fieldModifiers & Modifier.STATIC) != 0)
			umlAttribute.setStatic(true);
		
		attributes.add(umlAttribute);
	}
	return attributes;
}
 
Example #26
Source File: JdtFlags.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public static boolean isDefaultMethod(IMethodBinding method) {
	int modifiers= method.getModifiers();
	// https://bugs.eclipse.org/bugs/show_bug.cgi?id=405517#c7
	ITypeBinding declaringClass= method.getDeclaringClass();
	if (declaringClass.isInterface()) {
		return !Modifier.isAbstract(modifiers) && !Modifier.isStatic(modifiers);
	}
	return false;
}
 
Example #27
Source File: ModifierCorrectionSubProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private static Modifier findVisibilityModifier(List<IExtendedModifier> modifiers) {
	for (int i= 0; i < modifiers.size(); i++) {
		IExtendedModifier curr= modifiers.get(i);
		if (curr instanceof Modifier) {
			Modifier modifier= (Modifier) curr;
			ModifierKeyword keyword= modifier.getKeyword();
			if (keyword == ModifierKeyword.PUBLIC_KEYWORD || keyword == ModifierKeyword.PROTECTED_KEYWORD || keyword == ModifierKeyword.PRIVATE_KEYWORD) {
				return modifier;
			}
		}
	}
	return null;
}
 
Example #28
Source File: JdtBasedTypeFactory.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Returns a type reference for the given type binding. If the binding is null, an {@link JvmUnknownTypeReference unknown}
 * type reference is returned.
 */
// @NonNull 
protected JvmTypeReference createTypeReference(/* @Nullable */ ITypeBinding typeBinding) {
	if (typeBinding == null) {
		return TypesFactory.eINSTANCE.createJvmUnknownTypeReference();
	}
	if (typeBinding.isArray()) {
		ITypeBinding componentType = typeBinding.getComponentType();
		JvmTypeReference componentTypeReference = createTypeReference(componentType);
		JvmGenericArrayTypeReference typeReference = TypesFactory.eINSTANCE.createJvmGenericArrayTypeReference();
		typeReference.setComponentType(componentTypeReference);
		return typeReference;
	}
	ITypeBinding outer = null;
	if (typeBinding.isMember() && !Modifier.isStatic(typeBinding.getModifiers())) {
		outer = typeBinding.getDeclaringClass();
	}
	JvmParameterizedTypeReference result;
	if (outer != null) {
		JvmParameterizedTypeReference outerReference = (JvmParameterizedTypeReference) createTypeReference(outer);
		result = TypesFactory.eINSTANCE.createJvmInnerTypeReference();
		((JvmInnerTypeReference) result).setOuter(outerReference);
	} else {
		result = TypesFactory.eINSTANCE.createJvmParameterizedTypeReference();
	}
	ITypeBinding[] typeArguments = typeBinding.getTypeArguments();
	if (typeArguments.length != 0) {
		ITypeBinding erasure = typeBinding.getErasure();
		result.setType(createProxy(erasure));
		InternalEList<JvmTypeReference> arguments = (InternalEList<JvmTypeReference>)result.getArguments();
		for (int i = 0; i < typeArguments.length; i++) {
			JvmTypeReference argument = createTypeArgument(typeArguments[i]);
			arguments.addUnique(argument);
		}
	} else {
		result.setType(createProxy(typeBinding));
	}
	return result;
}
 
Example #29
Source File: MovedMemberAnalyzer.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private boolean isSourceAccess(IBinding binding) {
	if (binding instanceof IMethodBinding) {
		IMethodBinding method= (IMethodBinding)binding;
		return Modifier.isStatic(method.getModifiers()) && Bindings.equals(fSource, method.getDeclaringClass());
	} else if (binding instanceof ITypeBinding) {
		ITypeBinding type= (ITypeBinding)binding;
		return Modifier.isStatic(type.getModifiers()) && Bindings.equals(fSource, type.getDeclaringClass());
	} else if (binding instanceof IVariableBinding) {
		IVariableBinding field= (IVariableBinding)binding;
		return field.isField() && Modifier.isStatic(field.getModifiers()) && Bindings.equals(fSource, field.getDeclaringClass());
	}
	return false;
}
 
Example #30
Source File: ElementTypeTeller.java    From txtUML with Eclipse Public License 1.0 5 votes vote down vote up
public static boolean isFinal(FieldDeclaration node) {
	for (Object modifier : node.modifiers()) {
		if (modifier instanceof Modifier && ((Modifier) modifier).isFinal()) {
			return true;
		}
	}
	return false;
}