Java Code Examples for org.eclipse.jdt.core.dom.FieldDeclaration#fragments()

The following examples show how to use org.eclipse.jdt.core.dom.FieldDeclaration#fragments() . 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: CompilationUnitBuilder.java    From j2cl with 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 2
Source File: ExtractClassRefactoring.java    From Eclipse-Postfix-Code-Completion with 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 File: UiFieldProposalComputer.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 6 votes vote down vote up
private void addFieldProposal(List<ICompletionProposal> proposals,
    FieldDeclaration fieldDecl) {

  @SuppressWarnings("unchecked")
  List<VariableDeclarationFragment> fragments = fieldDecl.fragments();

  for (VariableDeclarationFragment fragment : fragments) {
    String fieldName = fragment.getName().getIdentifier();

    if (fieldName.startsWith(getEnteredText())) {
      proposals.add(new ReplacementCompletionProposal(fieldName,
          getReplaceOffset(), getReplaceLength(),
          ReplacementCompletionProposal.DEFAULT_CURSOR_POSITION, null,
          fieldName, XmlContentAssistUtilities.getImageForLocalVariable()));
    }
  }
}
 
Example 4
Source File: JavaASTVisitor.java    From SnowGraph with Apache License 2.0 6 votes vote down vote up
private List<FieldInfo> createFieldInfos(FieldDeclaration node, String belongTo) {
    List<FieldInfo> fieldInfos = new ArrayList<>();
    Type type = node.getType();
    Set<String> types = getTypes(type);
    String typeString = type.toString();
    String visibility = getVisibility(node);
    boolean isStatic = isStatic(node);
    boolean isFinal = isFinal(node);
    String comment = "";
    if (node.getJavadoc() != null)
        comment = sourceContent.substring(node.getJavadoc().getStartPosition(), node.getJavadoc().getStartPosition() + node.getJavadoc().getLength());
    List<VariableDeclarationFragment> fragments = node.fragments();
    for (VariableDeclarationFragment fragment : fragments) {
        FieldInfo fieldInfo = new FieldInfo();
        fieldInfo.belongTo = belongTo;
        fieldInfo.name = fragment.getName().getFullyQualifiedName();
        fieldInfo.typeString = typeString;
        fieldInfo.types = types;
        fieldInfo.visibility = visibility;
        fieldInfo.isFinal = isFinal;
        fieldInfo.isStatic = isStatic;
        fieldInfo.comment = comment;
        fieldInfos.add(fieldInfo);
    }
    return fieldInfos;
}
 
Example 5
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 6
Source File: ASTUtil.java    From spotbugs with 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 7
Source File: FieldDiff.java    From apidiff with MIT License 6 votes vote down vote up
/**
 * @param fieldInVersion1
 * @param fieldInVersion2
 * @return True, if there is a difference between the fields.
 */
private Boolean thereAreDifferentDefaultValueField(FieldDeclaration fieldInVersion1, FieldDeclaration fieldInVersion2){
	
	List<VariableDeclarationFragment> variable1Fragments = fieldInVersion1.fragments();
	List<VariableDeclarationFragment> variable2Fragments = fieldInVersion2.fragments();
	
	Expression valueVersion1 = variable1Fragments.get(0).getInitializer();
	Expression valueVersion2 = variable2Fragments.get(0).getInitializer();
	
	//If default value was removed/changed
	if((valueVersion1 == null && valueVersion2 != null) || (valueVersion1 != null && valueVersion2 == null)){
		return true;
	}
	
	//If fields have default value and they are different
	if((valueVersion1 != null && valueVersion2 != null) && (!valueVersion1.toString().equals(valueVersion2.toString()))){
		return true;
	}
	
	return false;
}
 
Example 8
Source File: ReplaceTypeCodeWithStateStrategy.java    From JDeodorant with 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 9
Source File: TypeResolver.java    From KodeBeagle with 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 10
Source File: ASTVisitors.java    From tassal with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public boolean visit(final FieldDeclaration node) {

	// Shift start position to after Javadoc (if present)
	shiftStartPosition(node);

	// Add to relevant containers
	final int line = cu.getLineNumber(node.getStartPosition());
	fieldLineRanges.add(Range.singleton(line).canonical(DiscreteDomain.integers()));
	fieldLineParentNodes.put(line, node.getParent());

	final Range<Integer> range = Range.closed(node.getStartPosition(),
			node.getStartPosition() + node.getLength() - 1);
	lineToFieldRanges.put(line, range);

	for (final Object fragment : node.fragments()) {
		final VariableDeclarationFragment frag = (VariableDeclarationFragment) fragment;

		// Split SIMPLE_NAME if token splitting enabled
		final SimpleName name = frag.getName();
		final ArrayList<String> identifiers = Lists.newArrayList();
		putSplitToken(identifiers, name.getIdentifier());
		for (final String identifier : identifiers)
			fieldIdentifiers.put(range, identifier);

		// Remove field identifiers from parent class
		final FoldableNode parentClass = foldableStack.peek();
		parentClass.removeTerms(identifiers);

	}
	return true;
}
 
Example 11
Source File: ReplaceTypeCodeWithStateStrategy.java    From JDeodorant with MIT License 5 votes vote down vote up
private void replacePrimitiveStateField() {
	ASTRewrite sourceRewriter = ASTRewrite.create(sourceTypeDeclaration.getAST());
	AST contextAST = sourceTypeDeclaration.getAST();
	ListRewrite contextBodyRewrite = sourceRewriter.getListRewrite(sourceTypeDeclaration, TypeDeclaration.BODY_DECLARATIONS_PROPERTY);
	FieldDeclaration[] fieldDeclarations = sourceTypeDeclaration.getFields();
	for(FieldDeclaration fieldDeclaration : fieldDeclarations) {
		List<VariableDeclarationFragment> fragments = fieldDeclaration.fragments();
		for(VariableDeclarationFragment fragment : fragments) {
			if(fragment.equals(typeCheckElimination.getTypeField())) {
				if(fragments.size() == 1) {
					ListRewrite fragmentsRewriter = sourceRewriter.getListRewrite(fieldDeclaration, FieldDeclaration.FRAGMENTS_PROPERTY);
					fragmentsRewriter.remove(fragment, null);
					VariableDeclarationFragment typeFragment = createStateFieldVariableDeclarationFragment(sourceRewriter, contextAST);
					fragmentsRewriter.insertLast(typeFragment, null);
					sourceRewriter.set(fieldDeclaration, FieldDeclaration.TYPE_PROPERTY, contextAST.newSimpleName(abstractClassName), null);
				}
			}
		}
	}
	try {
		TextEdit sourceEdit = sourceRewriter.rewriteAST();
		ICompilationUnit sourceICompilationUnit = (ICompilationUnit)sourceCompilationUnit.getJavaElement();
		CompilationUnitChange change = compilationUnitChanges.get(sourceICompilationUnit);
		change.getEdit().addChild(sourceEdit);
		change.addTextEditGroup(new TextEditGroup("Replace primitive type with State type", new TextEdit[] {sourceEdit}));
	} catch (JavaModelException e) {
		e.printStackTrace();
	}
}
 
Example 12
Source File: JavaApproximateVariableBindingExtractor.java    From tassal with BSD 3-Clause "New" or "Revised" License 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().getIdentifier());
	}
	return true;
}
 
Example 13
Source File: ASTReader.java    From JDeodorant with MIT License 5 votes vote down vote up
private void processFieldDeclaration(final ClassObject classObject, FieldDeclaration fieldDeclaration) {
	Type fieldType = fieldDeclaration.getType();
	ITypeBinding binding = fieldType.resolveBinding();
	List<CommentObject> fieldDeclarationComments = new ArrayList<CommentObject>();
	int fieldDeclarationStartPosition = fieldDeclaration.getStartPosition();
	int fieldDeclarationEndPosition = fieldDeclarationStartPosition + fieldDeclaration.getLength();
	for(CommentObject comment : classObject.commentList) {
		int commentStartPosition = comment.getStartPosition();
		int commentEndPosition = commentStartPosition + comment.getLength();
		if(fieldDeclarationStartPosition <= commentStartPosition && fieldDeclarationEndPosition >= commentEndPosition) {
			fieldDeclarationComments.add(comment);
		}
	}
	List<VariableDeclarationFragment> fragments = fieldDeclaration.fragments();
	for(VariableDeclarationFragment fragment : fragments) {
		String qualifiedName = binding.getQualifiedName();
		TypeObject typeObject = TypeObject.extractTypeObject(qualifiedName);
		typeObject.setArrayDimension(typeObject.getArrayDimension() + fragment.getExtraDimensions());
		FieldObject fieldObject = new FieldObject(typeObject, fragment.getName().getIdentifier());
		fieldObject.setClassName(classObject.getName());
		fieldObject.setVariableDeclarationFragment(fragment);
		fieldObject.addComments(fieldDeclarationComments);
		
		int fieldModifiers = fieldDeclaration.getModifiers();
		if((fieldModifiers & Modifier.PUBLIC) != 0)
			fieldObject.setAccess(Access.PUBLIC);
		else if((fieldModifiers & Modifier.PROTECTED) != 0)
			fieldObject.setAccess(Access.PROTECTED);
		else if((fieldModifiers & Modifier.PRIVATE) != 0)
			fieldObject.setAccess(Access.PRIVATE);
		else
			fieldObject.setAccess(Access.NONE);
		
		if((fieldModifiers & Modifier.STATIC) != 0)
			fieldObject.setStatic(true);
		
		classObject.addField(fieldObject);
	}
}
 
Example 14
Source File: JavaApproximateVariableBindingExtractor.java    From api-mining with GNU General Public License v3.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().getIdentifier());
	}
	return true;
}
 
Example 15
Source File: ClassFieldCollector.java    From SparkBuilderGenerator with MIT License 5 votes vote down vote up
private List<? extends BuilderField> findBuilderFieldsRecursively(TypeDeclaration currentOwnerClass) {
    List<BuilderField> builderFields = new ArrayList<>();

    if (preferencesManager.getPreferenceValue(INCLUDE_VISIBLE_FIELDS_FROM_SUPERCLASS)) {
        builderFields.addAll(getFieldsFromSuperclass(currentOwnerClass));
    }

    FieldDeclaration[] fields = currentOwnerClass.getFields();
    for (FieldDeclaration field : fields) {
        List<VariableDeclarationFragment> fragments = field.fragments();
        builderFields.addAll(getFilteredDeclarations(field, fragments));
    }
    return builderFields;
}
 
Example 16
Source File: ExtractClassRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
@Override
		public void fieldCreated(CompilationUnitRewrite cuRewrite, FieldDeclaration field, ParameterInfo pi) {
			FieldInfo fieldInfo= getFieldInfo(pi.getOldName());
			FieldDeclaration parent= (FieldDeclaration) fieldInfo.declaration.getParent();
			List<IExtendedModifier> modifiers= parent.modifiers();
			ListRewrite listRewrite= cuRewrite.getASTRewrite().getListRewrite(field, FieldDeclaration.MODIFIERS2_PROPERTY);
			for (Iterator<IExtendedModifier> iterator= modifiers.iterator(); iterator.hasNext();) {
				IExtendedModifier mod= iterator.next();
				//Temporarily disabled until initialization of final fields is handled correctly
//				if (mod.isModifier()) {
//					Modifier modifier= (Modifier) mod;
//					if (modifier.isFinal())
//						listRewrite.insertLast(moveNode(cuRewrite, modifier), null);
//				}
				if (mod.isAnnotation()) {
					listRewrite.insertFirst(moveNode(cuRewrite, (ASTNode) mod), null);
				}
			}
			if (fieldInfo.initializer != null && fieldInfo.hasFieldReference()) {
				List<VariableDeclarationFragment> fragments= field.fragments();
				for (Iterator<VariableDeclarationFragment> iterator= fragments.iterator(); iterator.hasNext();) {
					VariableDeclarationFragment vdf= iterator.next();
					vdf.setInitializer((Expression) moveNode(cuRewrite, fieldInfo.initializer));
				}
			}
			if (parent.getJavadoc() != null) {
				field.setJavadoc((Javadoc) moveNode(cuRewrite, parent.getJavadoc()));
			}
		}
 
Example 17
Source File: TypeParseVisitor.java    From SimFix with GNU General Public License v2.0 5 votes vote down vote up
public boolean visit(TypeDeclaration node) {
	Pair<String, String> clazzAndMethodName = NodeUtils.getTypeDecAndMethodDec(node.getName());
	String clazz = clazzAndMethodName.getFirst();
	AST ast = AST.newAST(AST.JLS8);
	Type type = ast.newSimpleType(ast.newSimpleName(clazz));
	ProjectInfo.addFieldType(clazz, "THIS", type);
	Type suType = node.getSuperclassType();
	if(suType != null){
		ProjectInfo.addFieldType(clazz, "SUPER", suType);
		ProjectInfo.addSuperClass(clazz, suType.toString());
	}
	
	List<Object> sInterfaces = node.superInterfaceTypes();
	if(sInterfaces != null){
		for(Object object : sInterfaces){
			if(object instanceof Type){
				Type interfaceType = (Type) object;
				ProjectInfo.addSuperInterface(clazz, interfaceType.toString());
			}
		}
	}
	
	FieldDeclaration fields[] = node.getFields();
	for (FieldDeclaration f : fields) {
		for (Object o : f.fragments()) {
			VariableDeclarationFragment vdf = (VariableDeclarationFragment) o;
			Type tmpType = f.getType();
			if(vdf.getExtraDimensions() > 0){
				tmpType = ast.newArrayType((Type) ASTNode.copySubtree(ast, tmpType), vdf.getExtraDimensions());
			}
			ProjectInfo.addFieldType(clazz, vdf.getName().toString(), tmpType);
		}
	}
	return true;
}
 
Example 18
Source File: FieldDeclarationWriter.java    From juniversal with MIT License 5 votes vote down vote up
@Override
public void write(FieldDeclaration fieldDeclaration) {
	// TODO: Handle final/const

	boolean isStatic = ASTUtil.containsStatic(fieldDeclaration.modifiers());

	if (getSourceFileWriter().getOutputType() == OutputType.HEADER && isStatic)
		write("static ");
	skipModifiers(fieldDeclaration.modifiers());

	// Write the type
	skipSpaceAndComments();
       writeType(fieldDeclaration.getType(), false);

	boolean first = true;
	for (Object fragment : fieldDeclaration.fragments()) {
		VariableDeclarationFragment variableDeclarationFragment = (VariableDeclarationFragment) fragment;

		if (! first) {
			copySpaceAndComments();
			matchAndWrite(",");
		}

		copySpaceAndComments();
		writeVariableDeclarationFragment(variableDeclarationFragment,
                   getSourceFileWriter().getOutputType() == OutputType.SOURCE);

		first = false;
	}

	copySpaceAndComments();
	matchAndWrite(";");
}
 
Example 19
Source File: UtilTools.java    From apidiff with MIT License 5 votes vote down vote up
public static String getFieldName(FieldDeclaration field){
	String name = null;
	List<VariableDeclarationFragment> variableFragments = field.fragments();
	for (VariableDeclarationFragment variableDeclarationFragment : variableFragments) {
		if(variableDeclarationFragment.resolveBinding() != null){
			name = variableDeclarationFragment.resolveBinding().getName();
		}
	}
	return name;
}
 
Example 20
Source File: SrcTreeGenerator.java    From sahagin-java with Apache License 2.0 5 votes vote down vote up
private IVariableBinding getVariableBinding(FieldDeclaration declaration) {
    for (Object fragment : declaration.fragments()) {
        if (fragment instanceof VariableDeclarationFragment) {
            VariableDeclarationFragment varDecl = (VariableDeclarationFragment) fragment;
            IVariableBinding binding = varDecl.resolveBinding();
            if (binding != null) {
                return binding;
            }
        }
    }
    return null;
}