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

The following examples show how to use org.eclipse.jdt.core.dom.FieldDeclaration. 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 Project: spring-javaformat   Author: spring-io   File: CodeLineBreakPreparator.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public boolean visit(FieldDeclaration node) {
	int index = this.tokenManager.lastIndexIn(node, TerminalTokens.TokenNameSEMICOLON);
	while (tokenIsOfType(index + 1, TerminalTokens.TokenNameCOMMENT_LINE,
			TerminalTokens.TokenNameCOMMENT_BLOCK)) {
		if (this.tokenManager.get(index).getLineBreaksAfter() > 0
				|| this.tokenManager.get(index + 1).getLineBreaksBefore() > 0) {
			break;
		}
		index++;
	}
	Token token = this.tokenManager.get(index);
	if (tokenIsOfType(index + 1, TerminalTokens.TokenNamestatic)) {
		return true;
	}
	token.clearLineBreaksAfter();
	token.putLineBreaksAfter(2);
	return true;
}
 
Example #2
Source Project: Eclipse-Postfix-Code-Completion   Author: trylimits   File: ExtractClassRefactoring.java    License: Eclipse Public License 1.0 6 votes vote down vote up
private void initializeDeclaration(TypeDeclaration node) {
	FieldDeclaration[] fields= node.getFields();
	for (int i= 0; i < fields.length; i++) {
		FieldDeclaration fieldDeclaration= fields[i];
		List<VariableDeclarationFragment> fragments= fieldDeclaration.fragments();
		for (Iterator<VariableDeclarationFragment> iterator= fragments.iterator(); iterator.hasNext();) {
			VariableDeclarationFragment vdf= iterator.next();
			FieldInfo fieldInfo= getFieldInfo(vdf.getName().getIdentifier());
			if (fieldInfo != null) {
				Assert.isNotNull(vdf);
				fieldInfo.declaration= vdf;
				fieldInfo.pi.setOldBinding(vdf.resolveBinding());
			}
		}
	}
}
 
Example #3
Source Project: apidiff   Author: aserg-ufmg   File: FieldDiff.java    License: MIT License 6 votes vote down vote up
/**
 * Searching changed fields type
 * @param version1
 * @param version2
 */
private void findChangedTypeFields(APIVersion version1, APIVersion version2) {
	for (TypeDeclaration type : version1.getApiAcessibleTypes()) {
		if(version2.containsAccessibleType(type)){
			for (FieldDeclaration fieldInVersion1 : type.getFields()) {
				if(!UtilTools.isVisibilityPrivate(fieldInVersion1) && !UtilTools.isVisibilityDefault(fieldInVersion1)){
					FieldDeclaration fieldInVersion2 = version2.getVersionField(fieldInVersion1, type);
					if(fieldInVersion2 != null && !UtilTools.isVisibilityPrivate(fieldInVersion2)){
						if(!fieldInVersion1.getType().toString().equals(fieldInVersion2.getType().toString())){
							String description = this.description.returnType(UtilTools.getFieldName(fieldInVersion2), UtilTools.getPath(type));
							this.addChange(type, fieldInVersion2, Category.FIELD_CHANGE_TYPE, true, description);
						}
					}
				}
			}
		}
	}
}
 
Example #4
Source Project: apidiff   Author: aserg-ufmg   File: FieldDiff.java    License: MIT License 6 votes vote down vote up
/**
 * Finding added fields
 * @param version1
 * @param version2
 */
private void findAddedFields(APIVersion version1, APIVersion version2) {
	for (TypeDeclaration typeVersion2 : version2.getApiAcessibleTypes()) {
		if(version1.containsAccessibleType(typeVersion2)){
			for (FieldDeclaration fieldInVersion2 : typeVersion2.getFields()) {
				String fullNameAndPath = this.getNameAndPath(fieldInVersion2, typeVersion2);
				if(!UtilTools.isVisibilityPrivate(fieldInVersion2) && !UtilTools.isVisibilityDefault(fieldInVersion2) && !this.fieldWithPathChanged.contains(fullNameAndPath)){
					FieldDeclaration fieldInVersion1;
						fieldInVersion1 = version1.getVersionField(fieldInVersion2, typeVersion2);
						if(fieldInVersion1 == null){
							String description = this.description.addition(UtilTools.getFieldName(fieldInVersion2), UtilTools.getPath(typeVersion2));
							this.addChange(typeVersion2, fieldInVersion2, Category.FIELD_ADD, false, description);
						}
				}
			}
		} 
	}
}
 
Example #5
Source Project: apidiff   Author: aserg-ufmg   File: FieldDiff.java    License: MIT License 6 votes vote down vote up
/**
 * Finding removed fields. If class was removed, class removal is a breaking change.
 * @param version1
 * @param version2
 */
private void findRemoveAndRefactoringFields(APIVersion version1, APIVersion version2) {
	for (TypeDeclaration type : version1.getApiAcessibleTypes()) {
		if(version2.containsAccessibleType(type)){
			for (FieldDeclaration fieldInVersion1 : type.getFields()) {
				if(!UtilTools.isVisibilityPrivate(fieldInVersion1)){
					FieldDeclaration fieldInVersion2 = version2.getVersionField(fieldInVersion1, type);
					if(fieldInVersion2 == null){
						Boolean refactoring = this.checkAndProcessRefactoring(fieldInVersion1, type);
						if(!refactoring){
							this.processRemoveField(fieldInVersion1, type);
						}
					}
				}
			}
		}
	}
}
 
Example #6
Source Project: JDeodorant   Author: tsantalis   File: ReplaceTypeCodeWithStateStrategy.java    License: MIT License 6 votes vote down vote up
private Set<MethodDeclaration> getMethodDeclarationsWithinAnonymousClassDeclarations(FieldDeclaration fieldDeclaration) {
	Set<MethodDeclaration> methods = new LinkedHashSet<MethodDeclaration>();
	List<VariableDeclarationFragment> fragments = fieldDeclaration.fragments();
	for(VariableDeclarationFragment fragment : fragments) {
		Expression expression = fragment.getInitializer();
		if(expression != null && expression instanceof ClassInstanceCreation) {
			ClassInstanceCreation classInstanceCreation = (ClassInstanceCreation)expression;
			AnonymousClassDeclaration anonymousClassDeclaration = classInstanceCreation.getAnonymousClassDeclaration();
			if(anonymousClassDeclaration != null) {
				List<BodyDeclaration> bodyDeclarations = anonymousClassDeclaration.bodyDeclarations();
				for(BodyDeclaration bodyDeclaration : bodyDeclarations) {
					if(bodyDeclaration instanceof MethodDeclaration)
						methods.add((MethodDeclaration)bodyDeclaration);
				}
			}
		}
	}
	return methods;
}
 
Example #7
Source Project: j2cl   Author: google   File: CompilationUnitBuilder.java    License: Apache License 2.0 6 votes vote down vote up
private List<Field> convert(FieldDeclaration fieldDeclaration) {
  List<Field> fields = new ArrayList<>();
  for (Object object : fieldDeclaration.fragments()) {
    org.eclipse.jdt.core.dom.VariableDeclarationFragment fragment =
        (org.eclipse.jdt.core.dom.VariableDeclarationFragment) object;
    Expression initializer;
    IVariableBinding variableBinding = fragment.resolveBinding();
    if (variableBinding.getConstantValue() == null) {
      initializer = convertOrNull(fragment.getInitializer());
    } else {
      initializer =
          convertConstantToLiteral(
              variableBinding.getConstantValue(),
              JdtUtils.createTypeDescriptor(variableBinding.getType()));
    }
    Field field =
        Field.Builder.from(JdtUtils.createFieldDescriptor(variableBinding))
            .setInitializer(initializer)
            .setSourcePosition(getSourcePosition(fieldDeclaration))
            .setNameSourcePosition(Optional.of(getSourcePosition(fragment.getName())))
            .build();
    fields.add(field);
  }
  return fields;
}
 
Example #8
Source Project: Eclipse-Postfix-Code-Completion   Author: trylimits   File: VariableDeclarationFix.java    License: Eclipse Public License 1.0 6 votes vote down vote up
private static ModifierChangeOperation createAddFinalOperation(SimpleName name, ASTNode decl) {
	if (decl == null)
		return null;

	IBinding binding= name.resolveBinding();
	if (!canAddFinal(binding, decl))
		return null;

	if (decl instanceof SingleVariableDeclaration) {
		return new ModifierChangeOperation(decl, new ArrayList<VariableDeclarationFragment>(), Modifier.FINAL, Modifier.NONE);
	} else if (decl instanceof VariableDeclarationExpression) {
		return new ModifierChangeOperation(decl, new ArrayList<VariableDeclarationFragment>(), Modifier.FINAL, Modifier.NONE);
	} else if (decl instanceof VariableDeclarationFragment){
		VariableDeclarationFragment frag= (VariableDeclarationFragment)decl;
		decl= decl.getParent();
		if (decl instanceof FieldDeclaration || decl instanceof VariableDeclarationStatement) {
			List<VariableDeclarationFragment> list= new ArrayList<VariableDeclarationFragment>();
			list.add(frag);
			return new ModifierChangeOperation(decl, list, Modifier.FINAL, Modifier.NONE);
		} else if (decl instanceof VariableDeclarationExpression) {
			return new ModifierChangeOperation(decl, new ArrayList<VariableDeclarationFragment>(), Modifier.FINAL, Modifier.NONE);
		}
	}

	return null;
}
 
Example #9
Source Project: Eclipse-Postfix-Code-Completion   Author: trylimits   File: ChangeTypeRefactoring.java    License: Eclipse Public License 1.0 6 votes vote down vote up
private static Type getType(ASTNode node) {
	switch(node.getNodeType()){
		case ASTNode.SINGLE_VARIABLE_DECLARATION:
			return ((SingleVariableDeclaration) node).getType();
		case ASTNode.FIELD_DECLARATION:
			return ((FieldDeclaration) node).getType();
		case ASTNode.VARIABLE_DECLARATION_STATEMENT:
			return ((VariableDeclarationStatement) node).getType();
		case ASTNode.VARIABLE_DECLARATION_EXPRESSION:
			return ((VariableDeclarationExpression) node).getType();
		case ASTNode.METHOD_DECLARATION:
			return ((MethodDeclaration)node).getReturnType2();
		case ASTNode.PARAMETERIZED_TYPE:
			return ((ParameterizedType)node).getType();
		default:
			Assert.isTrue(false);
			return null;
	}
}
 
Example #10
Source Project: JDeodorant   Author: tsantalis   File: ReplaceTypeCodeWithStateStrategy.java    License: 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 Project: Eclipse-Postfix-Code-Completion   Author: trylimits   File: ParameterObjectFactory.java    License: Eclipse Public License 1.0 6 votes vote down vote up
private FieldDeclaration createField(ParameterInfo pi, CompilationUnitRewrite cuRewrite) throws CoreException {
	AST ast= cuRewrite.getAST();
	ICompilationUnit unit= cuRewrite.getCu();

	VariableDeclarationFragment fragment= ast.newVariableDeclarationFragment();
	String lineDelim= StubUtility.getLineDelimiterUsed(unit);
	SimpleName fieldName= ast.newSimpleName(pi.getNewName());
	fragment.setName(fieldName);
	FieldDeclaration declaration= ast.newFieldDeclaration(fragment);
	if (createComments(unit.getJavaProject())) {
		String comment= StubUtility.getFieldComment(unit, pi.getNewTypeName(), pi.getNewName(), lineDelim);
		if (comment != null) {
			Javadoc doc= (Javadoc) cuRewrite.getASTRewrite().createStringPlaceholder(comment, ASTNode.JAVADOC);
			declaration.setJavadoc(doc);
		}
	}
	List<Modifier> modifiers= new ArrayList<Modifier>();
	if (fCreateGetter) {
		modifiers.add(ast.newModifier(ModifierKeyword.PRIVATE_KEYWORD));
	} else {
		modifiers.add(ast.newModifier(ModifierKeyword.PUBLIC_KEYWORD));
	}
	declaration.modifiers().addAll(modifiers);
	declaration.setType(importBinding(pi.getNewTypeBinding(), cuRewrite));
	return declaration;
}
 
Example #12
Source Project: jdt2famix   Author: feenkcom   File: InJavaImporter.java    License: 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 #13
private static boolean depends(IExpressionFragment selected, BodyDeclaration bd) {
	/* We currently consider selected to depend on bd only if db includes a declaration
	 * of a static field on which selected depends.
	 *
	 * A more accurate strategy might be to also check if bd contains (or is) a
	 * static initializer containing code which changes the value of a static field on
	 * which selected depends.  However, if a static is written to multiple times within
	 * during class initialization, it is difficult to predict which value should be used.
	 * This would depend on which value is used by expressions instances for which the new
	 * constant will be substituted, and there may be many of these; in each, the
	 * static field in question may have taken on a different value (if some of these uses
	 * occur within static initializers).
	 */

	if(bd instanceof FieldDeclaration) {
		FieldDeclaration fieldDecl = (FieldDeclaration) bd;
		for(Iterator<VariableDeclarationFragment> fragments = fieldDecl.fragments().iterator(); fragments.hasNext();) {
			VariableDeclarationFragment fragment = fragments.next();
			SimpleName staticFieldName = fragment.getName();
			if(selected.getSubFragmentsMatching(ASTFragmentFactory.createFragmentForFullSubtree(staticFieldName)).length != 0)
				return true;
		}
	}
	return false;
}
 
Example #14
Source Project: eclipse.jdt.ls   Author: eclipse   File: MoveHandler.java    License: Eclipse Public License 2.0 6 votes vote down vote up
private static BodyDeclaration getSelectedMemberDeclaration(ICompilationUnit unit, CodeActionParams params) {
	int start = DiagnosticsHelper.getStartOffset(unit, params.getRange());
	int end = DiagnosticsHelper.getEndOffset(unit, params.getRange());
	InnovationContext context = new InnovationContext(unit, start, end - start);
	context.setASTRoot(CodeActionHandler.getASTRoot(unit));

	ASTNode node = context.getCoveredNode();
	if (node == null) {
		node = context.getCoveringNode();
	}

	while (node != null && !(node instanceof BodyDeclaration)) {
		node = node.getParent();
	}

	if (node != null && (node instanceof MethodDeclaration || node instanceof FieldDeclaration || node instanceof AbstractTypeDeclaration) && JdtFlags.isStatic((BodyDeclaration) node)) {
		return (BodyDeclaration) node;
	}

	return null;
}
 
Example #15
Source Project: eclipse.jdt.ls   Author: eclipse   File: RefactorProposalUtility.java    License: Eclipse Public License 2.0 6 votes vote down vote up
private static boolean isMoveStaticMemberAvailable(ASTNode declaration) throws JavaModelException {
	if (declaration instanceof MethodDeclaration) {
		IMethodBinding method = ((MethodDeclaration) declaration).resolveBinding();
		return method != null && RefactoringAvailabilityTesterCore.isMoveStaticAvailable((IMember) method.getJavaElement());
	} else if (declaration instanceof FieldDeclaration) {
		List<IMember> members = new ArrayList<>();
		for (Object fragment : ((FieldDeclaration) declaration).fragments()) {
			IVariableBinding variable = ((VariableDeclarationFragment) fragment).resolveBinding();
			if (variable != null) {
				members.add((IField) variable.getJavaElement());
			}
		}
		return RefactoringAvailabilityTesterCore.isMoveStaticMembersAvailable(members.toArray(new IMember[0]));
	} else if (declaration instanceof AbstractTypeDeclaration) {
		ITypeBinding type = ((AbstractTypeDeclaration) declaration).resolveBinding();
		return type != null && RefactoringAvailabilityTesterCore.isMoveStaticAvailable((IType) type.getJavaElement());
	}

	return false;
}
 
Example #16
Source Project: JDeodorant   Author: tsantalis   File: MoveMethodRefactoring.java    License: MIT License 6 votes vote down vote up
private void addParameterToMovedMethod(MethodDeclaration newMethodDeclaration, SimpleName fieldName, ASTRewrite targetRewriter) {
	AST ast = newMethodDeclaration.getAST();
	SingleVariableDeclaration parameter = ast.newSingleVariableDeclaration();
	Type fieldType = null;
	FieldDeclaration[] fields = sourceTypeDeclaration.getFields();
	for(FieldDeclaration field : fields) {
		List<VariableDeclarationFragment> fragments = field.fragments();
		for(VariableDeclarationFragment fragment : fragments) {
			if(fragment.getName().getIdentifier().equals(fieldName.getIdentifier())) {
				fieldType = field.getType();
				break;
			}
		}
	}
	targetRewriter.set(parameter, SingleVariableDeclaration.TYPE_PROPERTY, fieldType, null);
	targetRewriter.set(parameter, SingleVariableDeclaration.NAME_PROPERTY, ast.newSimpleName(fieldName.getIdentifier()), null);
	ListRewrite parametersRewrite = targetRewriter.getListRewrite(newMethodDeclaration, MethodDeclaration.PARAMETERS_PROPERTY);
	parametersRewrite.insertLast(parameter, null);
	this.additionalArgumentsAddedToMovedMethod.add(fieldName.getIdentifier());
	this.additionalTypeBindingsToBeImportedInTargetClass.add(fieldType.resolveBinding());
	addParamTagElementToJavadoc(newMethodDeclaration, targetRewriter, fieldName.getIdentifier());
}
 
Example #17
Source Project: Eclipse-Postfix-Code-Completion   Author: trylimits   File: AddGetterSetterOperation.java    License: Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Generates a new setter method for the specified field
 * 
 * @param field the field
 * @param astRewrite the AST rewrite to use
 * @param rewrite the list rewrite to use
 * @throws CoreException if an error occurs
 * @throws OperationCanceledException if the operation has been cancelled
 */
private void generateSetterMethod(final IField field, ASTRewrite astRewrite, final ListRewrite rewrite) throws CoreException, OperationCanceledException {
	final IType type= field.getDeclaringType();
	final String name= GetterSetterUtil.getSetterName(field, null);
	final IMethod existing= JavaModelUtil.findMethod(name, new String[] { field.getTypeSignature()}, 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.getSetterStub(field, name, fSettings.createComments, fVisibility | (field.getFlags() & Flags.AccStatic)), rewrite, insertion);
		if (Flags.isFinal(field.getFlags())) {
			ASTNode fieldDecl= ASTNodes.getParent(NodeFinder.perform(fASTRoot, field.getNameRange()), FieldDeclaration.class);
			if (fieldDecl != null) {
				ModifierRewrite.create(astRewrite, fieldDecl).setModifiers(0, Modifier.FINAL, null);
			}
		}

	}
}
 
Example #18
Source Project: spotbugs   Author: spotbugs   File: ASTUtil.java    License: GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * Returns the <CODE>FieldDeclaration</CODE> for the specified field name.
 * The field has to be declared in the specified
 * <CODE>TypeDeclaration</CODE>.
 *
 * @param type
 *            The <CODE>TypeDeclaration</CODE>, where the
 *            <CODE>FieldDeclaration</CODE> is declared in.
 * @param fieldName
 *            The simple field name to search for.
 * @return the <CODE>FieldDeclaration</CODE> found in the specified
 *         <CODE>TypeDeclaration</CODE>.
 * @throws FieldDeclarationNotFoundException
 *             if no matching <CODE>FieldDeclaration</CODE> was found.
 */
public static FieldDeclaration getFieldDeclaration(TypeDeclaration type, String fieldName)
        throws FieldDeclarationNotFoundException {
    requireNonNull(type, "type declaration");
    requireNonNull(fieldName, "field name");

    for (FieldDeclaration field : type.getFields()) {
        for (Object fragObj : field.fragments()) {
            VariableDeclarationFragment fragment = (VariableDeclarationFragment) fragObj;
            if (fieldName.equals(fragment.getName().getIdentifier())) {
                return field;
            }
        }
    }

    throw new FieldDeclarationNotFoundException(type, fieldName);
}
 
Example #19
Source Project: Eclipse-Postfix-Code-Completion   Author: trylimits   File: HierarchyProcessor.java    License: 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 #20
Source Project: Eclipse-Postfix-Code-Completion   Author: trylimits   File: ExtractMethodAnalyzer.java    License: Eclipse Public License 1.0 5 votes vote down vote up
@Override
public boolean visit(VariableDeclarationFragment node) {
	boolean result= super.visit(node);
	if (isFirstSelectedNode(node)) {
		if (node.getParent() instanceof FieldDeclaration) {
			invalidSelection(RefactoringCoreMessages.ExtractMethodAnalyzer_cannot_extract_variable_declaration_fragment_from_field, JavaStatusContext.create(fCUnit, node));
		} else {
			invalidSelection(RefactoringCoreMessages.ExtractMethodAnalyzer_cannot_extract_variable_declaration_fragment, JavaStatusContext.create(fCUnit, node));
		}
		return false;
	}
	return result;
}
 
Example #21
Source Project: tassal   Author: mast-group   File: UsagePointExtractor.java    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public boolean visit(final FieldDeclaration node) {
	if (className.contains(node.getType().toString())) {
		interestingNodes.add(node.getParent());
	}
	return false;
}
 
Example #22
Source Project: KodeBeagle   Author: Imaginea   File: TypeResolver.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Looks for field declarations (i.e. class member variables).
 */
@Override
public boolean visit(final FieldDeclaration node) {
	for (final Object fragment : node.fragments()) {
		final VariableDeclarationFragment frag = (VariableDeclarationFragment) fragment;
		addBinding(node, frag.getName(), node.getType());
	}
	return true;
}
 
Example #23
Source Project: Eclipse-Postfix-Code-Completion   Author: trylimits   File: JavaParseTreeBuilder.java    License: Eclipse Public License 1.0 5 votes vote down vote up
private String getFieldName(VariableDeclarationFragment node) {
    StringBuffer buffer= new StringBuffer();
    buffer.append(node.getName().toString());
    ASTNode parent= node.getParent();
    if (parent instanceof FieldDeclaration) {
        FieldDeclaration fd= (FieldDeclaration) parent;
        buffer.append(" : "); //$NON-NLS-1$
        buffer.append(getType(fd.getType()));
    }
    return buffer.toString();
}
 
Example #24
Source Project: sahagin-java   Author: SahaginOrg   File: SrcTreeGenerator.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public boolean visit(FieldDeclaration node) {
    IVariableBinding variable = getVariableBinding(node);
    if (variable == null) {
        return super.visit(node);
    }
    ITypeBinding classBinding = variable.getDeclaringClass();
    if (!classBinding.isClass() && !classBinding.isInterface()) {
        // enum method, etc
        return super.visit(node);
    }

    // TODO support additional testDoc for Field
    String testDoc = ASTUtils.getTestDoc(variable, locales);
    if (testDoc == null) {
        return super.visit(node);
    }

    TestClass testClass = classBindingTestClass(classBinding);
    TestField testField = new TestField();
    testField.setTestClassKey(testClass.getKey());
    testField.setTestClass(testClass);
    testField.setKey(testClass.getKey() + "." + variable.getName());
    testField.setSimpleName(variable.getName());
    testField.setTestDoc(testDoc);
    testField.setValue(null); // TODO currently not supported
    fieldTable.addTestField(testField);

    testClass.addTestFieldKey(testField.getKey());
    testClass.addTestField(testField);

    return super.visit(node);
}
 
Example #25
private TextEditGroup makeDeclarationPrivate(ASTRewrite rewriter, FieldDeclaration decl) {
	TextEditGroup description= new TextEditGroup(RefactoringCoreMessages.SelfEncapsulateField_change_visibility);
	VariableDeclarationFragment[] vdfs= new VariableDeclarationFragment[] { fFieldDeclaration };
	int includedModifiers= Modifier.PRIVATE;
	int excludedModifiers= Modifier.PROTECTED | Modifier.PUBLIC;
	VariableDeclarationRewrite.rewriteModifiers(decl, vdfs, includedModifiers, excludedModifiers, rewriter, description);
	return description;
}
 
Example #26
Source Project: apidiff   Author: aserg-ufmg   File: FieldDiff.java    License: MIT License 5 votes vote down vote up
/**
 * Finding deprecated fields
 * @param version1
 * @param version2
 */
private void findAddedDeprecatedFields(APIVersion version1, APIVersion version2) {
	for(TypeDeclaration typeVersion2 : version2.getApiAcessibleTypes()){
		for(FieldDeclaration fieldVersion2 : typeVersion2.getFields()){
			if(this.isFieldAccessible(fieldVersion2) && this.isDeprecated(fieldVersion2, typeVersion2)){
				FieldDeclaration fieldInVersion1 = version1.getVersionField(fieldVersion2, typeVersion2);
				if(fieldInVersion1 == null || !this.isDeprecated(fieldInVersion1, version1.getVersionAccessibleType(typeVersion2))){
					String description = this.description.deprecate(UtilTools.getFieldName(fieldVersion2), UtilTools.getPath(typeVersion2));
					this.addChange(typeVersion2, fieldVersion2, Category.FIELD_DEPRECATED, false, description);
				}
			}
		}
	}
}
 
Example #27
Source Project: compiler   Author: boalang   File: TestQ22.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public boolean visit(FieldDeclaration node) {
	field ++;
	org.eclipse.jdt.core.dom.Type type = node.getType();
	if (type instanceof SimpleType && ((SimpleType)type).getName().getFullyQualifiedName().equals("String")) {
		stringField += node.fragments().size();
		stringField2 += node.fragments().size();
	}
	return true;
}
 
Example #28
Source Project: Eclipse-Postfix-Code-Completion   Author: trylimits   File: FullConstraintCreator.java    License: Eclipse Public License 1.0 5 votes vote down vote up
@Override
public ITypeConstraint[] create(FieldDeclaration fd){
	List<ITypeConstraint> result= new ArrayList<ITypeConstraint>();
	result.addAll(Arrays.asList(getConstraintsFromFragmentList(fd.fragments(), fd.getType())));
	result.addAll(getConstraintsForHiding(fd));
	result.addAll(getConstraintsForFieldDeclaringTypes(fd));
	return result.toArray(new ITypeConstraint[result.size()]);
}
 
Example #29
Source Project: ck   Author: mauricioaniche   File: NumberOfFields.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void visit(FieldDeclaration node) {
	fields++;
	fieldNames.addAll(getVariableName(node.fragments()));

	boolean isPublic = Modifier.isPublic(node.getModifiers());
	boolean isPrivate = Modifier.isPrivate(node.getModifiers());
	boolean isProtected = Modifier.isProtected(node.getModifiers());

	if(isPublic)
		publicFields++;
	else if(isPrivate)
		privateFields++;
	else if(isProtected)
		protectedFields++;
	else
		defaultFields++;

	// other characteristics rather than visibility
	boolean isStatic = Modifier.isStatic(node.getModifiers());
	boolean isFinal = Modifier.isFinal(node.getModifiers());
	boolean isSynchronized = Modifier.isSynchronized(node.getModifiers());
	
	if(isStatic)
		staticFields++;

	if(isFinal)
		finalFields++;

	if(isSynchronized)
		synchronizedFields++;

}
 
Example #30
Source Project: apidiff   Author: aserg-ufmg   File: FieldDiff.java    License: MIT License 5 votes vote down vote up
/**
 * Finding change in final modifier
 * 
 * @param version1
 * @param version2
 */
private void findChangedFinal(APIVersion version1, APIVersion version2) {
	for (TypeDeclaration typeInVersion1 : version1.getApiAcessibleTypes()) {
		if(version2.containsType(typeInVersion1)){//Se type ainda existe.
			for(FieldDeclaration fieldVersion1: typeInVersion1.getFields()){
				FieldDeclaration fieldVersion2 = version2.getVersionField(fieldVersion1, typeInVersion1);
				if(this.isFieldAccessible(fieldVersion1) && (fieldVersion2 != null)){
					this.diffModifierFinal(typeInVersion1, fieldVersion1, fieldVersion2);
				}
			}
		}
	}
}