Example usage for org.eclipse.jdt.core IType getDeclaringType

List of usage examples for org.eclipse.jdt.core IType getDeclaringType

Introduction

In this page you can find the example usage for org.eclipse.jdt.core IType getDeclaringType.

Prototype

IType getDeclaringType();

Source Link

Document

Returns the type in which this member is declared, or null if this member is not declared in a type (for example, a top-level type).

Usage

From source file:at.bestsolution.fxide.jdt.corext.util.MethodOverrideTester.java

License:Open Source License

private String getVariableSubstitution(IMember context, String variableName) throws JavaModelException {
    IType type;
    if (context instanceof IMethod) {
        String subst = getMethodSubstitions((IMethod) context).getSubstitution(variableName);
        if (subst != null) {
            return subst;
        }//from w w w . j a  v a2s .  c o m
        type = context.getDeclaringType();
    } else {
        type = (IType) context;
    }
    String subst = getTypeSubstitions(type).getSubstitution(variableName);
    if (subst != null) {
        return subst;
    }
    IJavaElement parent = type.getParent();
    if (parent instanceof IMethod) {
        return getVariableSubstitution((IMethod) parent, variableName);
    } else if (type.getDeclaringType() != null) {
        return getVariableSubstitution(type.getDeclaringType(), variableName);
    }
    return variableName; // not a type variable
}

From source file:at.bestsolution.fxide.jdt.corext.util.MethodOverrideTester.java

License:Open Source License

private String getVariableErasure(IMember context, String variableName) throws JavaModelException {
    IType type;
    if (context instanceof IMethod) {
        String subst = getMethodSubstitions((IMethod) context).getErasure(variableName);
        if (subst != null) {
            return subst;
        }/* w w w . j  a  v  a 2 s. com*/
        type = context.getDeclaringType();
    } else {
        type = (IType) context;
    }
    String subst = getTypeSubstitions(type).getErasure(variableName);
    if (subst != null) {
        return subst;
    }
    IJavaElement parent = type.getParent();
    if (parent instanceof IMethod) {
        return getVariableErasure((IMethod) parent, variableName);
    } else if (type.getDeclaringType() != null) {
        return getVariableErasure(type.getDeclaringType(), variableName);
    }
    return variableName; // not a type variable
}

From source file:at.bestsolution.fxide.jdt.text.javadoc.JavadocContentAccess2.java

License:Open Source License

private boolean handleValueTag(TagElement node) {

    List<? extends ASTNode> fragments = node.fragments();
    try {//from   w w w  .j  a v  a 2s . c o m
        if (!(fElement instanceof IMember)) {
            return false;
        }
        if (fragments.isEmpty()) {
            if (fElement instanceof IField && JdtFlags.isStatic((IField) fElement)
                    && JdtFlags.isFinal((IField) fElement)) {
                IField field = (IField) fElement;
                return handleConstantValue(field, false);
            }
        } else if (fragments.size() == 1) {
            Object first = fragments.get(0);
            if (first instanceof MemberRef) {
                MemberRef memberRef = (MemberRef) first;
                if (memberRef.getQualifier() == null) {
                    SimpleName name = memberRef.getName();
                    IType type = fElement instanceof IType ? (IType) fElement
                            : ((IMember) fElement).getDeclaringType();
                    while (type != null) {
                        IField field = type.getField(name.getIdentifier());
                        if (field != null && field.exists()) {
                            if (JdtFlags.isStatic(field) && JdtFlags.isFinal(field))
                                return handleConstantValue(field, true);
                            break;
                        }
                        type = type.getDeclaringType();
                    }
                }
            }
        }
    } catch (JavaModelException e) {
        //TODO
        e.printStackTrace();
    }

    return false;
}

From source file:at.bestsolution.fxide.jdt.text.viewersupport.JavaElementLabelComposer.java

License:Open Source License

/**
 * Appends the label for a type. Considers the T_* flags.
 *
 * @param type the element to render//from www  .  j  a  v  a  2  s  .  com
 * @param flags the rendering flags. Flags with names starting with 'T_' are considered.
 */
public void appendTypeLabel(IType type, long flags) {

    if (getFlag(flags, JavaElementLabels.T_FULLY_QUALIFIED)) {
        IPackageFragment pack = type.getPackageFragment();
        if (!pack.isDefaultPackage()) {
            appendPackageFragmentLabel(pack, (flags & QUALIFIER_FLAGS));
            fBuffer.append('.');
        }
    }
    IJavaElement parent = type.getParent();
    if (getFlag(flags, JavaElementLabels.T_FULLY_QUALIFIED | JavaElementLabels.T_CONTAINER_QUALIFIED)) {
        IType declaringType = type.getDeclaringType();
        if (declaringType != null) {
            appendTypeLabel(declaringType, JavaElementLabels.T_CONTAINER_QUALIFIED | (flags & QUALIFIER_FLAGS));
            fBuffer.append('.');
        }
        int parentType = parent.getElementType();
        if (parentType == IJavaElement.METHOD || parentType == IJavaElement.FIELD
                || parentType == IJavaElement.INITIALIZER) { // anonymous or local
            appendElementLabel(parent, 0);
            fBuffer.append('.');
        }
    }

    String typeName;
    boolean isAnonymous = false;
    if (type.isLambda()) {
        typeName = "() -> {...}"; //$NON-NLS-1$
        try {
            String[] superInterfaceSignatures = type.getSuperInterfaceTypeSignatures();
            if (superInterfaceSignatures.length > 0) {
                typeName = typeName + ' ' + getSimpleTypeName(type, superInterfaceSignatures[0]);
            }
        } catch (JavaModelException e) {
            //ignore
        }

    } else {
        typeName = getElementName(type);
        try {
            isAnonymous = type.isAnonymous();
        } catch (JavaModelException e1) {
            // should not happen, but let's play safe:
            isAnonymous = typeName.length() == 0;
        }
        if (isAnonymous) {
            try {
                if (parent instanceof IField && type.isEnum()) {
                    typeName = '{' + JavaElementLabels.ELLIPSIS_STRING + '}';
                } else {
                    String supertypeName = null;
                    String[] superInterfaceSignatures = type.getSuperInterfaceTypeSignatures();
                    if (superInterfaceSignatures.length > 0) {
                        supertypeName = getSimpleTypeName(type, superInterfaceSignatures[0]);
                    } else {
                        String supertypeSignature = type.getSuperclassTypeSignature();
                        if (supertypeSignature != null) {
                            supertypeName = getSimpleTypeName(type, supertypeSignature);
                        }
                    }
                    if (supertypeName == null) {
                        typeName = JavaUIMessages.JavaElementLabels_anonym;
                    } else {
                        typeName = Messages.format(JavaUIMessages.JavaElementLabels_anonym_type, supertypeName);
                    }
                }
            } catch (JavaModelException e) {
                //ignore
                typeName = JavaUIMessages.JavaElementLabels_anonym;
            }
        }
    }
    fBuffer.append(typeName);

    if (getFlag(flags, JavaElementLabels.T_TYPE_PARAMETERS)) {
        if (getFlag(flags, JavaElementLabels.USE_RESOLVED) && type.isResolved()) {
            BindingKey key = new BindingKey(type.getKey());
            if (key.isParameterizedType()) {
                String[] typeArguments = key.getTypeArguments();
                appendTypeArgumentSignaturesLabel(type, typeArguments, flags);
            } else {
                String[] typeParameters = Signature.getTypeParameters(key.toSignature());
                appendTypeParameterSignaturesLabel(typeParameters, flags);
            }
        } else if (type.exists()) {
            try {
                appendTypeParametersLabels(type.getTypeParameters(), flags);
            } catch (JavaModelException e) {
                // ignore
            }
        }
    }

    // category
    if (getFlag(flags, JavaElementLabels.T_CATEGORY) && type.exists()) {
        try {
            appendCategoryLabel(type, flags);
        } catch (JavaModelException e) {
            // ignore
        }
    }

    // post qualification
    if (getFlag(flags, JavaElementLabels.T_POST_QUALIFIED)) {
        int offset = fBuffer.length();
        fBuffer.append(JavaElementLabels.CONCAT_STRING);
        IType declaringType = type.getDeclaringType();
        if (declaringType == null && type.isBinary() && isAnonymous) {
            // workaround for Bug 87165: [model] IType#getDeclaringType() does not work for anonymous binary type
            String tqn = type.getTypeQualifiedName();
            int lastDollar = tqn.lastIndexOf('$');
            if (lastDollar != 1) {
                String declaringTypeCF = tqn.substring(0, lastDollar) + ".class"; //$NON-NLS-1$
                declaringType = type.getPackageFragment().getClassFile(declaringTypeCF).getType();
                try {
                    ISourceRange typeSourceRange = type.getSourceRange();
                    if (declaringType.exists() && SourceRange.isAvailable(typeSourceRange)) {
                        IJavaElement realParent = declaringType.getTypeRoot()
                                .getElementAt(typeSourceRange.getOffset() - 1);
                        if (realParent != null) {
                            parent = realParent;
                        }
                    }
                } catch (JavaModelException e) {
                    // ignore
                }
            }
        }
        if (declaringType != null) {
            appendTypeLabel(declaringType, JavaElementLabels.T_FULLY_QUALIFIED | (flags & QUALIFIER_FLAGS));
            int parentType = parent.getElementType();
            if (parentType == IJavaElement.METHOD || parentType == IJavaElement.FIELD
                    || parentType == IJavaElement.INITIALIZER) { // anonymous or local
                fBuffer.append('.');
                appendElementLabel(parent, 0);
            }
        } else {
            appendPackageFragmentLabel(type.getPackageFragment(), flags & QUALIFIER_FLAGS);
        }
        //         if (getFlag(flags, JavaElementLabels.COLORIZE)) {
        //            fBuffer.setStyle(offset, fBuffer.length() - offset, QUALIFIER_STYLE);
        //         }
    }
}

From source file:ch.qos.logback.beagle.util.EditorUtil.java

License:Open Source License

private static String getFullyQualifiedName(IType type) {
    try {//from www  . ja  v  a  2s .c  o  m
        if (type.isBinary() && !type.isAnonymous()) {
            IType declaringType = type.getDeclaringType();
            if (declaringType != null) {
                return getFullyQualifiedName(declaringType) + '.' + type.getElementName();
            }
        }
    } catch (JavaModelException e) {
        // ignore
    }
    return type.getFullyQualifiedName('.');
}

From source file:com.android.ide.eclipse.adt.internal.project.BaseProjectHelper.java

License:Open Source License

/**
 * Tests that a class name is valid for usage in the manifest.
 * <p/>//from w ww  .  ja  va  2  s .  co m
 * This tests the class existence, that it can be instantiated (ie it must not be abstract,
 * nor non static if enclosed), and that it extends the proper super class (not necessarily
 * directly)
 * @param javaProject the {@link IJavaProject} containing the class.
 * @param className the fully qualified name of the class to test.
 * @param superClassName the fully qualified name of the expected super class.
 * @param testVisibility if <code>true</code>, the method will check the visibility of the class
 * or of its constructors.
 * @return {@link #TEST_CLASS_OK} or an error message.
 */
public final static String testClassForManifest(IJavaProject javaProject, String className,
        String superClassName, boolean testVisibility) {
    try {
        // replace $ by .
        String javaClassName = className.replaceAll("\\$", "\\."); //$NON-NLS-1$ //$NON-NLS-2$

        // look for the IType object for this class
        IType type = javaProject.findType(javaClassName);
        if (type != null && type.exists()) {
            // test that the class is not abstract
            int flags = type.getFlags();
            if (Flags.isAbstract(flags)) {
                return String.format("%1$s is abstract", className);
            }

            // test whether the class is public or not.
            if (testVisibility && Flags.isPublic(flags) == false) {
                // if its not public, it may have a public default constructor,
                // which would then be fine.
                IMethod basicConstructor = type.getMethod(type.getElementName(), new String[0]);
                if (basicConstructor != null && basicConstructor.exists()) {
                    int constructFlags = basicConstructor.getFlags();
                    if (Flags.isPublic(constructFlags) == false) {
                        return String.format(
                                "%1$s or its default constructor must be public for the system to be able to instantiate it",
                                className);
                    }
                } else {
                    return String.format(
                            "%1$s must be public, or the system will not be able to instantiate it.",
                            className);
                }
            }

            // If it's enclosed, test that it's static. If its declaring class is enclosed
            // as well, test that it is also static, and public.
            IType declaringType = type;
            do {
                IType tmpType = declaringType.getDeclaringType();
                if (tmpType != null) {
                    if (tmpType.exists()) {
                        flags = declaringType.getFlags();
                        if (Flags.isStatic(flags) == false) {
                            return String.format("%1$s is enclosed, but not static",
                                    declaringType.getFullyQualifiedName());
                        }

                        flags = tmpType.getFlags();
                        if (testVisibility && Flags.isPublic(flags) == false) {
                            return String.format("%1$s is not public", tmpType.getFullyQualifiedName());
                        }
                    } else {
                        // if it doesn't exist, we need to exit so we may as well mark it null.
                        tmpType = null;
                    }
                }
                declaringType = tmpType;
            } while (declaringType != null);

            // test the class inherit from the specified super class.
            // get the type hierarchy
            ITypeHierarchy hierarchy = type.newSupertypeHierarchy(new NullProgressMonitor());

            // if the super class is not the reference class, it may inherit from
            // it so we get its supertype. At some point it will be null and we
            // will stop
            IType superType = type;
            boolean foundProperSuperClass = false;
            while ((superType = hierarchy.getSuperclass(superType)) != null && superType.exists()) {
                if (superClassName.equals(superType.getFullyQualifiedName())) {
                    foundProperSuperClass = true;
                }
            }

            // didn't find the proper superclass? return false.
            if (foundProperSuperClass == false) {
                return String.format("%1$s does not extend %2$s", className, superClassName);
            }

            return TEST_CLASS_OK;
        } else {
            return String.format("Class %1$s does not exist", className);
        }
    } catch (JavaModelException e) {
        return String.format("%1$s: %2$s", className, e.getMessage());
    }
}

From source file:com.architexa.diagrams.relo.jdt.ParseUtilities.java

License:Open Source License

static private TypeDeclaration findTypeDeclaration(CompilationUnit cu, IType type) throws JavaModelException {
    IType declaringType = type.getDeclaringType();
    if (declaringType == null) {
        Iterator<?> topLevelTypeDeclIt = cu.types().iterator();
        while (topLevelTypeDeclIt.hasNext()) {
            AbstractTypeDeclaration td = (AbstractTypeDeclaration) topLevelTypeDeclIt.next();
            if (td.getName().getIdentifier().equals(type.getElementName()))
                return (TypeDeclaration) td;
        }/*from  ww  w  .  ja v a 2s.c o  m*/
    } else {
        TypeDeclaration declaringTD = findTypeDeclaration(cu, declaringType);
        TypeDeclaration[] siblingTD = declaringTD.getTypes();
        for (int i = 0; i < siblingTD.length; i++) {
            if (siblingTD[i].getName().getIdentifier().equals(type.getElementName()))
                return siblingTD[i];
        }
    }

    logger.error("Could not find type for: " + type.getFullyQualifiedName());
    return null;
}

From source file:com.cb.eclipse.folding.java.calculation.TypeStrategy.java

License:Open Source License

public void postScan(int position, IJavaElement elem) throws JavaModelException {
    ISourceRange range = getNaturalRange(elem);
    IType type = (IType) elem;

    boolean collapse;
    boolean fold;

    boolean negateLine = FoldingPlugin.getBoolean(PreferenceKeys.LAST_LINE_TYPES);
    if (type.getDeclaringType() != null) { // inner class
        collapse = FoldingPlugin.getBoolean(PreferenceKeys.COLLAPSE_INNER_TYPES);
        fold = FoldingPlugin.getBoolean(PreferenceKeys.FOLD_INNER_TYPES);
    } else { // top level type
        collapse = FoldingPlugin.getBoolean(PreferenceKeys.COLLAPSE_TOP_TYPES);
        fold = FoldingPlugin.getBoolean(PreferenceKeys.FOLD_TOP_TYPES);
    }//from ww w  . j av a  2s .co m

    if (fold) {

        addRegion(new EnhancedPosition(position, range.getOffset() + (range.getLength() - position),
                new JavaPositionMetadata(false, negateLine, collapse, false, null)));
    }

}

From source file:com.codenvy.ide.ext.java.server.core.search.SearchPattern.java

License:Open Source License

/**
 * Returns the enclosing type names of the given type.
 *///from  ww  w  . j av  a  2s .c  om
private static char[][] enclosingTypeNames(IType type) {
    IJavaElement parent = type.getParent();
    switch (parent.getElementType()) {
    case IJavaElement.CLASS_FILE:
        // For a binary type, the parent is not the enclosing type, but the declaring type is.
        // (see bug 20532  Declaration of member binary type not found)
        IType declaringType = type.getDeclaringType();
        if (declaringType == null)
            return CharOperation.NO_CHAR_CHAR;
        return CharOperation.arrayConcat(enclosingTypeNames(declaringType),
                declaringType.getElementName().toCharArray());
    case IJavaElement.COMPILATION_UNIT:
        return CharOperation.NO_CHAR_CHAR;
    case IJavaElement.FIELD:
    case IJavaElement.INITIALIZER:
    case IJavaElement.METHOD:
        IType declaringClass = ((IMember) parent).getDeclaringType();
        return CharOperation.arrayConcat(enclosingTypeNames(declaringClass),
                new char[][] { declaringClass.getElementName().toCharArray(), IIndexConstants.ONE_STAR });
    case IJavaElement.TYPE:
        return CharOperation.arrayConcat(enclosingTypeNames((IType) parent),
                parent.getElementName().toCharArray());
    default:
        return null;
    }
}

From source file:com.codenvy.ide.ext.java.server.internal.core.BinaryType.java

License:Open Source License

public String getSourceFileName(IBinaryType info) {
    if (info == null) {
        try {//from   ww w .  ja  v  a 2s.  c o m
            info = (IBinaryType) getElementInfo();
        } catch (JavaModelException e) {
            // default to using the outer most declaring type name
            IType type = this;
            IType enclosingType = getDeclaringType();
            while (enclosingType != null) {
                type = enclosingType;
                enclosingType = type.getDeclaringType();
            }
            return type.getElementName() + Util.defaultJavaExtension();
        }
    }
    return sourceFileName(info);
}