Java 类org.eclipse.jdt.core.IField 实例源码

项目:che    文件:FieldProposalInfo.java   
/**
 * 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 org.eclipse.jdt.core.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;
}
项目:java-builders-generator    文件:GenerateBuildersHandler.java   
@Override
public Object execute(final ExecutionEvent event) throws ExecutionException {

    final IEditorPart editorPart = HandlerUtil.getActiveEditor(event);
    final ICompilationUnit icu = JavaUI.getWorkingCopyManager().getWorkingCopy(editorPart.getEditorInput());

    try {
        final IType type = icu.getTypes()[0];
        final List<Field> fields = new ArrayList<>();
        for (final IField field : type.getFields()) {
            final String fieldName = field.getElementName();
            final String fieldType = Signature.getSignatureSimpleName(field.getTypeSignature());
            fields.add(new Field(fieldName, fieldType));
        }

        new WizardDialog(HandlerUtil.getActiveShell(event), new BuilderGeneratorWizard(icu, fields)).open();

    }
    catch (final JavaModelException e) {
        e.printStackTrace();
    }

    return null;
}
项目:pandionj    文件:StaticInvocationWidget.java   
private void addRefCombovalues(Combo combo, String paramType) {
    if(!PrimitiveType.isPrimitiveSig(paramType)) {
        combo.add("null");
        IType owner = (IType) method.getParent();
        try {
            IField[] fields = owner.getFields();
            for(IField f : fields)
                if(Flags.isStatic(f.getFlags()) && f.getTypeSignature().equals(paramType))
                    combo.add(f.getElementName());


        } catch (JavaModelException e1) {
            e1.printStackTrace();
        }
    }
}
项目:pandionj    文件:StaticInvocationWidget.java   
private void addCombovalues(Combo combo, String paramType) {
    if(!PrimitiveType.isPrimitiveSig(paramType)) {
        String sel = combo.getText();
        combo.removeAll();
        combo.add("null");
        IType owner = (IType) method.getParent();
        try {
            IField[] fields = owner.getFields();
            for(IField f : fields)
                if(Flags.isStatic(f.getFlags()) && f.getTypeSignature().equals(paramType))
                    combo.add(f.getElementName());


        } catch (JavaModelException e1) {
            e1.printStackTrace();
        }
        if(sel.isEmpty())
            combo.select(0);
        else
            combo.setText(sel);
    }
}
项目:mesfavoris    文件:JavaTypeMemberBookmarkLocationProvider.java   
private List<IMember> getMemberCandidates(IType type, Bookmark javaBookmark) {
    String elementKind = javaBookmark.getPropertyValue(PROP_JAVA_ELEMENT_KIND);
    String elementName = javaBookmark.getPropertyValue(PROP_JAVA_ELEMENT_NAME);
    if (KIND_FIELD.equals(elementKind)) {
        IField field = type.getField(elementName);
        return field.exists() ? Lists.newArrayList(field) : Collections.emptyList();
    }
    if (KIND_METHOD.equals(elementKind)) {
        String signature = javaBookmark.getPropertyValue(PROP_JAVA_METHOD_SIGNATURE);
        IMethod method = null;
        if (signature != null) {
            method = getMethod(type, elementName, signature);
        }
        if (method == null) {
            List<IMethod> candidates = getMethodsWithName(type, elementName);
            return Lists.newArrayList(candidates);
        }
        return Lists.newArrayList(method);
    }
    if (JavaEditorUtils.isType(elementKind) && elementName != null) {
        IType memberType = type.getType(elementName);
        return memberType.exists() ? Lists.newArrayList(memberType) : Collections.emptyList();
    }
    return Collections.emptyList();
}
项目:mesfavoris    文件:JavaTypeMemberBookmarkPropertiesProvider.java   
protected void addMemberBookmarkProperties(Map<String, String> bookmarkProperties, IMember member) {
    putIfAbsent(bookmarkProperties, PROP_JAVA_ELEMENT_NAME, member.getElementName());
    if (member.getDeclaringType() != null) {
        putIfAbsent(bookmarkProperties, PROP_JAVA_DECLARING_TYPE,
                member.getDeclaringType().getFullyQualifiedName());
    }
    putIfAbsent(bookmarkProperties, PROP_JAVA_ELEMENT_KIND, getKind(member));
    if (member instanceof IMethod) {
        putIfAbsent(bookmarkProperties, PROP_JAVA_METHOD_SIGNATURE,
                JavaEditorUtils.getMethodSimpleSignature((IMethod) member));
        putIfAbsent(bookmarkProperties, Bookmark.PROPERTY_NAME,
                bookmarkProperties.get(PROP_JAVA_DECLARING_TYPE) + '.' + member.getElementName() + "()");
    }
    if (member instanceof IType) {
        IType type = (IType) member;
        putIfAbsent(bookmarkProperties, PROP_JAVA_TYPE, type.getFullyQualifiedName());
        putIfAbsent(bookmarkProperties, Bookmark.PROPERTY_NAME, type.getFullyQualifiedName());
    }
    if (member instanceof IField) {
        putIfAbsent(bookmarkProperties, Bookmark.PROPERTY_NAME,
                bookmarkProperties.get(PROP_JAVA_DECLARING_TYPE) + '.' + member.getElementName());
    }
    putIfAbsent(bookmarkProperties, Bookmark.PROPERTY_NAME, member.getElementName());
}
项目:Sparrow    文件:OutCodeVisitor.java   
@Override
public boolean visit(FieldDeclaration fieldDeclaration) {
    List<VariableDeclarationFragment> fragments = fieldDeclaration.fragments();
    for (VariableDeclarationFragment fragment : fragments) {
        IVariableBinding binding = fragment.resolveBinding();
        if (binding == null)
            continue;
        IField field = (IField) binding.getJavaElement();
        FieldDetails fieldDetails = new FieldDetails();
        fieldDetails.setModifiers(fieldDeclaration.getModifiers());
        allDetails.put(field.getHandleIdentifier(), fieldDetails);
    }
    return true;
}
项目:Sparrow    文件:OutCodeVisitor.java   
@Override
public boolean visit(SimpleName node) {
    if (currentMethod == null)
        return false;
    IBinding binding = node.resolveBinding();
    if (binding == null)
        return false;
    if (node.isDeclaration())
        return true;
    if (node.resolveBinding() instanceof IVariableBinding) {
        IVariableBinding iVariableBinding = (IVariableBinding) node.resolveBinding();
        if (iVariableBinding.isField()) {
            IVariableBinding variableDeclarationBinding = iVariableBinding.getVariableDeclaration();
            if (variableDeclarationBinding.getDeclaringClass() != null) {
                IJavaElement accessedField = variableDeclarationBinding.getJavaElement();
                if (accessedField instanceof IField) {
                    if (!((IField) accessedField).isReadOnly())
                        methodDetails.addAccess((IField) accessedField);
                }
            }
        }
    }
    return true;
}
项目:datahierarchy    文件:AddToFilterAction.java   
private List<String> getTypesToFilter(IStructuredSelection selection) {
    if (selection == null) {
        return null;
    }
    List<String> typesToFilter = new ArrayList<String>();
    for (Iterator<?> iterator = selection.iterator(); iterator.hasNext();) {
        Object elt = iterator.next();
        if(elt instanceof TreeElement<?,?>){
            elt = ((TreeElement)elt).getJavaElement();
        }
        if (elt instanceof IField) {
            IField field = (IField) elt;
            String resolvedType = SearchUtils.getResolvedType(field);
            if (resolvedType != null) {
                typesToFilter.add(resolvedType);
            }
        } else if(elt instanceof IType){
            IType type = (IType) elt;
            typesToFilter.add(type.getFullyQualifiedName());
        }
    }
    return typesToFilter;
}
项目:Constants-to-Enum-Eclipse-Plugin    文件:ConvertToEnumTypePage.java   
private void createEnumTypeNameField(final Composite parent) {
    final Label label= new Label(parent, SWT.NONE);
    label.setText(Messages.ConvertToEnumTypePage_EnumName);
    label.setLayoutData(new GridData());

    fNameField= new Text(parent, SWT.BORDER);
    fNameField.addModifyListener(new ModifyListener() {
        public void modifyText(ModifyEvent e) {
            handleNameChanged(fNameField.getText());
        }
    });
    fNameField.setLayoutData(new GridData(GridData.FILL, GridData.CENTER, true, false));
    IField[] fields = (IField[]) getConvertToEnumRefactoring().getFieldsToRefactor().toArray(new IField[] {});
    List fieldList = new ArrayList(fields.length);
    for (int i = 0; i < fields.length; i++) {
        IField field = fields[i];
        fieldList.add(field.getElementName());
    }
    String suggestedName = getSuggestedEnumTypeName((String[]) fieldList.toArray(new String[]{}));
    fNameField.setText(suggestedName);
}
项目:Constants-to-Enum-Eclipse-Plugin    文件:ConvertToEnumTypePage.java   
/**
 * Handles the name changed event.
 *
 * @param name
 *            the name
 */
protected void handleNameChanged(final String name) {
    if (name != null) {

        String packageName = Util.getPackageName(name);
        if ( packageName.isEmpty() && !getConvertToEnumRefactoring().getFieldsToRefactor().isEmpty() ) {
            //assign package to be the package of the first constant.
            //TODO [rk]: Done just to avoid default package for now.
            IField field = (IField) getConvertToEnumRefactoring().getFieldsToRefactor().iterator().next();
            IType parent = (IType) field.getParent();
            String fullyQualifiedName = parent.getFullyQualifiedName();
            packageName = Util.getPackageName(fullyQualifiedName);
        }

        getConvertToEnumRefactoring().setPackageName(packageName);

        String simpleName = Util.getSimpleName(name);
        getConvertToEnumRefactoring().setSimpleTypeName(simpleName);
    }
    checkPageCompletionStatus(true);
}
项目:jenerate    文件:FieldDialogImpl.java   
public FieldDialogImpl(CommandIdentifier commandIdentifier, Shell parentShell, String dialogTitle, IField[] fields,
        LinkedHashSet<StrategyIdentifier> possibleStrategies, boolean disableAppendSuper,
        PreferencesManager preferencesManager, IDialogSettings dialogSettings,
        LinkedHashMap<String, IJavaElement> insertPositions, DialogStrategyManager dialogStrategyManager) {
    super(parentShell);
    this.commandIdentifier = commandIdentifier;
    this.generalDialogSettings = dialogSettings;
    this.dialogStrategyManager = dialogStrategyManager;
    setShellStyle(SWT.DIALOG_TRIM | SWT.APPLICATION_MODAL | SWT.RESIZE);
    this.title = dialogTitle;
    this.allFields = fields;
    this.disableAppendSuper = disableAppendSuper;
    this.preferencesManager = preferencesManager;
    this.possibleStrategies = possibleStrategies;
    this.insertPositions = insertPositions;
    this.fieldDialogSettings = initFieldDialogSettings();
    initCurrentStrategy();
    currentDialogStrategy.configureSpecificDialogSettings(generalDialogSettings);
}
项目:Constants-to-Enum-Eclipse-Plugin    文件:Util.java   
public static Collection getDistinctSets(Collection elementSets)
        throws JavaModelException {
    final Collection ret = new LinkedHashSet(elementSets);
    for (final Iterator it = elementSets.iterator(); it.hasNext();) {
        final Collection set = (Collection) it.next();
        final Collection constValues = new ArrayList();
        for (final Iterator jit = set.iterator(); jit.hasNext();) {
            final IJavaElement elem = (IJavaElement) jit.next();
            if (elem.getElementType() == IJavaElement.FIELD) {
                final IField field = (IField) elem;
                final Object constValue = field.getConstant();
                if (constValue != null)
                    constValues.add(constValue);
            }
        }

        if (!distinct(constValues))
            ret.remove(set);
    }
    return ret;
}
项目:VRaptorEclipsePlugin    文件:ObjectReferenceValidator.java   
private void validateObjectTree(ExpressionReference e, IncludedObject object) throws JavaModelException, ExpressionLanguageException {
    IType type = object.getFieldType();
    int currentSegment = 1;
    if (type != null) {
        while (currentSegment < e.getSegmentCount()) {
            String name = e.getSegment(currentSegment++);
            IField field = type.getField(name);
            if (field == null) {
                throw new ExpressionLanguageException(name + " not included in " +
                                controller.getName(), expression.getLocation());
            } else {
                type = field.getDeclaringType();
            }
        }
    }
}
项目:che    文件:RefactoringManager.java   
private static RenameSupport createRenameSupport(IJavaElement element, String newName, int flags)
    throws CoreException {
  switch (element.getElementType()) {
    case IJavaElement.PACKAGE_FRAGMENT:
      return RenameSupport.create((IPackageFragment) element, newName, flags);
    case IJavaElement.COMPILATION_UNIT:
      return RenameSupport.create((ICompilationUnit) element, newName, flags);
    case IJavaElement.TYPE:
      return RenameSupport.create((IType) element, newName, flags);
    case IJavaElement.METHOD:
      final IMethod method = (IMethod) element;
      if (method.isConstructor())
        return createRenameSupport(method.getDeclaringType(), newName, flags);
      else return RenameSupport.create((IMethod) element, newName, flags);
    case IJavaElement.FIELD:
      return RenameSupport.create((IField) element, newName, flags);
    case IJavaElement.TYPE_PARAMETER:
      return RenameSupport.create((ITypeParameter) element, newName, flags);
    case IJavaElement.LOCAL_VARIABLE:
      return RenameSupport.create((ILocalVariable) element, newName, flags);
  }
  return null;
}
项目:jenerate    文件:FieldDialogImpl.java   
@Override
public boolean close() {
    List<Object> list = Arrays.asList(fieldViewer.getCheckedElements());
    selectedFields = list.toArray(new IField[list.size()]);

    if (DialogFactoryHelperImpl.FIRST_METHOD_POSITION.equals(currentPosition)
            || DialogFactoryHelperImpl.LAST_METHOD_POSITION.equals(currentPosition)) {
        fieldDialogSettings.put(SETTINGS_INSERT_POSITION, currentPosition);
    }

    if (!disableAppendSuper) {
        fieldDialogSettings.put(SETTINGS_APPEND_SUPER, appendSuper);
    }
    fieldDialogSettings.put(SETTINGS_GENERATE_COMMENT, generateComment);
    fieldDialogSettings.put(SETTINGS_USE_GETTERS, useGettersInsteadOfFields);

    currentDialogStrategy.callbackBeforeDialogClosing();
    currentDialogStrategy.disposeSpecificComponents();
    return super.close();
}
项目:jenerate    文件:DialogFactoryHelperImpl.java   
private IField[] getNonStaticNonCacheFields(IType objectClass, PreferencesManager preferencesManager)
        throws JavaModelException {
    Set<String> cacheFields = new HashSet<>();
    cacheFields.add(preferencesManager.getCurrentPreferenceValue(JeneratePreferences.HASHCODE_CACHING_FIELD));
    cacheFields.add(preferencesManager.getCurrentPreferenceValue(JeneratePreferences.TOSTRING_CACHING_FIELD));

    IField[] fields;
    fields = objectClass.getFields();

    List<IField> result = new ArrayList<>();

    for (int i = 0, size = fields.length; i < size; i++) {
        if (!Flags.isStatic(fields[i].getFlags()) && !cacheFields.contains(fields[i].getElementName())) {
            result.add(fields[i]);
        }
    }

    return result.toArray(new IField[result.size()]);
}
项目:datahierarchy    文件:DelayedJavaElement.java   
@Override
public synchronized void setInitialized(boolean initialized) {
    boolean wasInitialized = super.isInitialized();
    super.setInitialized(initialized);
    if (initialized) {
        synchronized (jobLock) {
            job = null;
        }
    } else {
        if (wasInitialized) {
            synchronized (jobLock) {
                for (TreeElement<C, ?> child : super.getChildren(null)) {
                    child.setInitialized(false);
                    removeChild(child);
                }
            }
        }
    }
    if (getData() instanceof IType) {
        remember((IType) getData(), this);
    } else if (getData() instanceof IField) {
        remember((IField) getData(), this);
    }
}
项目:che    文件:GetterSetterCompletionProposal.java   
public GetterSetterCompletionProposal(
    IField field, int start, int length, boolean isGetter, int relevance)
    throws JavaModelException {
  super(
      "",
      field.getCompilationUnit(),
      start,
      length,
      JavaPluginImages.get(JavaPluginImages.DESC_MISC_PUBLIC),
      getDisplayName(field, isGetter),
      relevance); // $NON-NLS-1$
  Assert.isNotNull(field);

  fField = field;
  fIsGetter = isGetter;
  setProposalInfo(new ProposalInfo(field));
}
项目:jenerate    文件:CommonsLangToStringMethodContent.java   
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();
}
项目:jenerate    文件:MethodContentGenerations.java   
/**
 * Creates the hashCode method content given a certain hashCode method name for delegation
 * 
 * @param hashCodeMethodName the hashCode method name that process the hash
 * @param data the data to extract configuration from
 * @return the hashCode method content
 * @throws JavaModelException if a problem occurs during the code generation.
 */
public static String createHashCodeContent(String hashCodeMethodName, EqualsHashCodeGenerationData data)
        throws JavaModelException {
    StringBuffer content = new StringBuffer();
    content.append("return Objects.");
    content.append(hashCodeMethodName);
    content.append("(");
    if (data.appendSuper()) {
        content.append("super.hashCode(), ");
    }
    IField[] checkedFields = data.getCheckedFields();
    String prefix = "";
    for (IField checkedField : checkedFields) {
        content.append(prefix);
        prefix = ", ";
        content.append(
                MethodContentGenerations.getFieldAccessorString(checkedField, data.useGettersInsteadOfFields()));
    }
    content.append(");\n");
    return content.toString();
}
项目:che    文件:RenameFieldProcessor.java   
private RefactoringStatus checkNestedHierarchy(IType type) throws CoreException {
  IType[] nestedTypes = type.getTypes();
  if (nestedTypes == null) return null;
  RefactoringStatus result = new RefactoringStatus();
  for (int i = 0; i < nestedTypes.length; i++) {
    IField otherField = nestedTypes[i].getField(getNewElementName());
    if (otherField.exists()) {
      String msg =
          Messages.format(
              RefactoringCoreMessages.RenameFieldRefactoring_hiding,
              new String[] {
                BasicElementLabels.getJavaElementName(fField.getElementName()),
                BasicElementLabels.getJavaElementName(getNewElementName()),
                BasicElementLabels.getJavaElementName(nestedTypes[i].getFullyQualifiedName('.'))
              });
      result.addWarning(msg, JavaStatusContext.create(otherField));
    }
    result.merge(checkNestedHierarchy(nestedTypes[i]));
  }
  return result;
}
项目:che    文件:RenameFieldProcessor.java   
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;
}
项目:jenerate    文件:CommonsLangHashCodeMethodContent.java   
private static String createHashCodeBuilderString(EqualsHashCodeGenerationData data) throws JavaModelException {
    StringBuffer content = new StringBuffer();
    content.append("new HashCodeBuilder(");
    content.append(data.getInitMultNumbers().getValue());
    content.append(")");
    if (data.appendSuper()) {
        content.append(".appendSuper(super.hashCode())");
    }
    IField[] checkedFields = data.getCheckedFields();
    for (int i = 0; i < checkedFields.length; i++) {
        content.append(".append(");
        content.append(MethodContentGenerations.getFieldAccessorString(checkedFields[i],
                data.useGettersInsteadOfFields()));
        content.append(")");
    }
    content.append(".toHashCode();\n");

    return content.toString();
}
项目:che    文件:GenericRefactoringHandleTransplanter.java   
protected IType transplantHandle(IJavaElement parent, IType element) {
  switch (parent.getElementType()) {
    case IJavaElement.COMPILATION_UNIT:
      return ((ICompilationUnit) parent).getType(element.getElementName());
    case IJavaElement.CLASS_FILE:
      return ((IClassFile) parent).getType();
    case IJavaElement.METHOD:
      return ((IMethod) parent).getType(element.getElementName(), element.getOccurrenceCount());
    case IJavaElement.FIELD:
      return ((IField) parent).getType(element.getElementName(), element.getOccurrenceCount());
    case IJavaElement.INITIALIZER:
      return ((IInitializer) parent)
          .getType(element.getElementName(), element.getOccurrenceCount());
    case IJavaElement.TYPE:
      return ((IType) parent).getType(element.getElementName(), element.getOccurrenceCount());
    default:
      throw new IllegalStateException(element.toString());
  }
}
项目:che    文件:SourceMapper.java   
/** @see org.eclipse.jdt.internal.compiler.ISourceElementRequestor */
public void enterField(FieldInfo fieldInfo) {
  if (this.typeDepth >= 0) {
    this.memberDeclarationStart[this.typeDepth] = fieldInfo.declarationStart;
    this.memberNameRange[this.typeDepth] =
        new SourceRange(
            fieldInfo.nameSourceStart, fieldInfo.nameSourceEnd - fieldInfo.nameSourceStart + 1);
    String fieldName = new String(fieldInfo.name);
    this.memberName[this.typeDepth] = fieldName;

    // categories
    IType currentType = this.types[this.typeDepth];
    IField field = currentType.getField(fieldName);
    addCategories(field, fieldInfo.categories);
  }
}
项目:jenerate    文件:GuavaToStringMethodContent.java   
@Override
public String getMethodContent(IType objectClass, ToStringGenerationData data) throws Exception {
    StringBuffer content = new StringBuffer();
    content.append("return MoreObjects.toStringHelper(this)");
    if (data.appendSuper()) {
        content.append(".add(\"super\", super.toString())");
    }
    IField[] checkedFields = data.getCheckedFields();
    for (IField checkedField : checkedFields) {
        content.append(".add(\"");
        content.append(checkedField.getElementName());
        content.append("\", ");
        content.append(
                MethodContentGenerations.getFieldAccessorString(checkedField, data.useGettersInsteadOfFields()));
        content.append(")");
    }
    content.append(".toString();\n");
    return content.toString();
}
项目:che    文件:RefactoringAvailabilityTester.java   
public static boolean isExtractSupertypeAvailable(IMember member) throws JavaModelException {
  if (!member.exists()) return false;
  final int type = member.getElementType();
  if (type != IJavaElement.METHOD && type != IJavaElement.FIELD && type != IJavaElement.TYPE)
    return false;
  if (JdtFlags.isEnum(member) && type != IJavaElement.TYPE) return false;
  if (!Checks.isAvailable(member)) return false;
  if (member instanceof IMethod) {
    final IMethod method = (IMethod) member;
    if (method.isConstructor()) return false;
    if (JdtFlags.isNative(method)) return false;
    member = method.getDeclaringType();
  } else if (member instanceof IField) {
    member = member.getDeclaringType();
  }
  if (member instanceof IType) {
    if (JdtFlags.isEnum(member) || JdtFlags.isAnnotation(member)) return false;
    if (member.getDeclaringType() != null && !JdtFlags.isStatic(member)) return false;
    if (((IType) member).isAnonymous())
      return false; // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=253727
    if (((IType) member).isLambda()) return false;
  }
  return true;
}
项目:che    文件:RefactoringAvailabilityTester.java   
public static boolean isGeneralizeTypeAvailable(final IJavaElement element)
    throws JavaModelException {
  if (element != null && element.exists()) {
    String type = null;
    if (element instanceof IMethod) type = ((IMethod) element).getReturnType();
    else if (element instanceof IField) {
      final IField field = (IField) element;
      if (JdtFlags.isEnum(field)) return false;
      type = field.getTypeSignature();
    } else if (element instanceof ILocalVariable) return true;
    else if (element instanceof IType) {
      final IType clazz = (IType) element;
      if (JdtFlags.isEnum(clazz)) return false;
      return true;
    }
    if (type == null || PrimitiveType.toCode(Signature.toString(type)) != null) return false;
    return true;
  }
  return false;
}
项目:che    文件:RefactoringAvailabilityTester.java   
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;
}
项目:pandionj    文件:ObjectModel.java   
private boolean isFieldVisible(IField m) {
        try {
            int f = m.getFlags();
            return  !Flags.isStatic(f) && isVisibleMember(m);
        }
        catch (JavaModelException e) {
//          e.printStackTrace();
            return false;
        }
    }
项目:o3smeasures-tool    文件:LackCohesionMethodsJavaModel.java   
/**
 * @see IJavaModel#calculateValue
 */
@Override
public void calculateValue(ICompilationUnit unit) {

    IMethod[] iMethods = null;
    IField[] iFields = null;
    try {
        IType[] iTypes = unit.getTypes();

        for (IType iType : iTypes){
            iMethods = iType.getMethods();
            iFields = iType.getFields();
        }

        if ((iFields != null && iMethods != null) && (iFields.length > 1 && iMethods.length > 1)) {
            for (IField field: iFields){
                sharedAttributesPerMethods.put(field.getElementName(), new HashSet<String>());
                nonSharedAttributesPerMethods.put(field.getElementName(), new HashSet<String>());
            }
            for (IMethod method: iMethods){
                connectedComponents.put(method.getElementName(), new HashSet<String>());
            }
            checkMethodsWithSharedAttributes(iMethods);

            if (LCOMType.LCOM.toString() == getLcomType()){
                setLcomValue(calculateLCOMValue());
            }else if (LCOMType.LCOM2.toString() == getLcomType()){
                setLcom2Value(calculateLCOM2Value());
            }else{
                setLcom4Value(calculateLCOM4Value());
            }
        }
    } catch (JavaModelException exception) {
        logger.error(exception);
    }
}
项目:eclipse.jdt.ls    文件:PotentialProgrammingProblemsFix.java   
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);
            }
        }
    }
}
项目:eclipse.jdt.ls    文件:PotentialProgrammingProblemsFix.java   
private void collectChildrenWithMissingSerialVersionId(IJavaElement[] children, IType serializable, List<IType> result) throws JavaModelException {
    for (int i = 0; i < children.length; i++) {
        IJavaElement child = children[i];
        if (child instanceof IType) {
            IType type = (IType) child;

            if (type.isClass()) {
                IField field = type.getField(NAME_FIELD);
                if (!field.exists()) {
                    ITypeHierarchy hierarchy = type.newSupertypeHierarchy(new NullProgressMonitor());
                    IType[] interfaces = hierarchy.getAllSuperInterfaces(type);
                    for (int j = 0; j < interfaces.length; j++) {
                        if (interfaces[j].equals(serializable)) {
                            result.add(type);
                            break;
                        }
                    }
                }
            }

            collectChildrenWithMissingSerialVersionId(type.getChildren(), serializable, result);
        } else if (child instanceof IMethod) {
            collectChildrenWithMissingSerialVersionId(((IMethod) child).getChildren(), serializable, result);
        } else if (child instanceof IField) {
            collectChildrenWithMissingSerialVersionId(((IField) child).getChildren(), serializable, result);
        }
    }
}
项目:eclipse.jdt.ls    文件:JavaElementLabelComposer.java   
/**
 * Appends the style label for a field. Considers the F_* flags.
 *
 * @param field the element to render
 * @param flags the rendering flags. Flags with names starting with 'F_' are considered.
 */
public void appendFieldLabel(IField field, long flags) {
    try {

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

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

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

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

    } catch (JavaModelException e) {
        JavaLanguageServerPlugin.logException("", e); // NotExistsException will not reach this point
    }
}
项目:eclipse.jdt.ls    文件:SelfEncapsulateFieldProposal.java   
public SelfEncapsulateFieldProposal(String label, ICompilationUnit targetCU, ASTNode invocationNode, IVariableBinding binding, IField field, int relevance) {
    super(label, targetCU, null, relevance);

    this.fField = field;
    this.fVariableBinding = binding;
    this.fSenderBinding = binding.getDeclaringClass();
    this.fNode = invocationNode;
}
项目:eclipse.jdt.ls    文件:GetterSetterCorrectionSubProcessor.java   
private static CUCorrectionProposal getProposal(ProposalParameter context) {
    IJavaElement element = context.variableBinding.getJavaElement();
    if (element instanceof IField) {
        IField field = (IField) element;
        CompilationUnit cu = SharedASTProvider.getInstance().getAST(field.getTypeRoot(), null);
        try {
            if (isSelfEncapsulateAvailable(field)) {
                return new SelfEncapsulateFieldProposal(getDescription(field), field.getCompilationUnit(), cu.getRoot(), context.variableBinding, field, IProposalRelevance.GETTER_SETTER_UNUSED_PRIVATE_FIELD);
            }
        } catch (JavaModelException e) {
            JavaLanguageServerPlugin.logException("Add getter proposal failure ", e);
        }
    }
    return null;
}
项目:code    文件:EclipseJavaUtil.java   
public static String getMemberTypeAsString(IField f) {
    if(f == null) return null;
    try {
        String typeName = new String(Signature.toCharArray(f.getTypeSignature().toCharArray()));
        return resolveType(f.getDeclaringType(), typeName);
    } catch (JavaModelException e) {
        e.printStackTrace();
    }
    return null;
}
项目:Sparrow    文件:MethodDetails.java   
public void addAccess(IField accessedField) {
    Integer accessCount = accesses.get(accessedField);
    if (accessCount == null) {
        accessCount = 1;
    } else
        accessCount += 1;
    accesses.put(accessedField, accessCount);
}
项目:Sparrow    文件:ModelVisitor.java   
private String visitIFields(ICompilationUnit unit, IType type, OutCodeVisitor visitor, int indentation, Set<String> unresolvedTypes) throws JavaModelException {
    IField[] fields = type.getFields();
    String content = "";
    for (IField field : fields) {
        content += serializeField(unit, indentation, field, visitor, unresolvedTypes);
    }
    return content;
}