Java Code Examples for org.eclipse.jdt.core.dom.ITypeBinding#getPackage()
The following examples show how to use
org.eclipse.jdt.core.dom.ITypeBinding#getPackage() .
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: Binding2JavaModel.java From lapse-plus with GNU General Public License v3.0 | 6 votes |
public static ICompilationUnit findCompilationUnit(ITypeBinding typeBinding, IJavaProject project) throws JavaModelException { if (!typeBinding.isFromSource()) { return null; } while (typeBinding != null && !typeBinding.isTopLevel()) { typeBinding= typeBinding.getDeclaringClass(); } if (typeBinding != null) { IPackageBinding pack= typeBinding.getPackage(); String packageName= pack.isUnnamed() ? "" : pack.getName(); //$NON-NLS-1$ IType type= project.findType(packageName, typeBinding.getName()); if (type != null) { return type.getCompilationUnit(); } } return null; }
Example 2
Source File: JdtBasedTypeFactory.java From xtext-eclipse with Eclipse Public License 2.0 | 6 votes |
private JvmDeclaredType createType(IType type, ITypeBinding binding) { // Maintain a string builder we pass along during recursion // that contains the prefix for the fully qualified name of the binding instance being traversed. // StringBuilder fqn = new StringBuilder(100); IPackageBinding packageBinding = binding.getPackage(); String packageName = null; if (packageBinding != null && !packageBinding.isUnnamed()) { packageName = packageBinding.getName(); fqn.append(packageBinding.getName()); fqn.append('.'); } JvmDeclaredType result = createType(binding, type.getHandleIdentifier(), Lists.<String>newArrayList(), fqn); result.setPackageName(packageName); return result; }
Example 3
Source File: ScopeAnalyzer.java From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 | 6 votes |
/** * Evaluates if the declaration is visible in a certain context. * @param binding The binding of the declaration to examine * @param context The context to test in * @return Returns */ public static boolean isVisible(IBinding binding, ITypeBinding context) { if (binding.getKind() == IBinding.VARIABLE && !((IVariableBinding) binding).isField()) { return true; // all local variables found are visible } ITypeBinding declaring= getDeclaringType(binding); if (declaring == null) { return false; } declaring= declaring.getTypeDeclaration(); int modifiers= binding.getModifiers(); if (Modifier.isPublic(modifiers) || declaring.isInterface()) { return true; } else if (Modifier.isProtected(modifiers) || !Modifier.isPrivate(modifiers)) { if (declaring.getPackage() == context.getPackage()) { return true; } return isTypeInScope(declaring, context, Modifier.isProtected(modifiers)); } // private visibility return isTypeInScope(declaring, context, false); }
Example 4
Source File: ReferenceResolvingVisitor.java From windup with Eclipse Public License 1.0 | 6 votes |
private ClassReference processTypeBinding(ITypeBinding type, ResolutionStatus resolutionStatus, TypeReferenceLocation referenceLocation, int lineNumber, int columnNumber, int length, String line) { if (type == null) return null; final String sourceString = getQualifiedName(type); final String packageName; if (type.getPackage() != null) packageName = type.getPackage().getName(); else packageName = PackageAndClassName.parseFromQualifiedName(sourceString).packageName; final String className = type.getName(); return processTypeAsString(sourceString, packageName, className, resolutionStatus, referenceLocation, lineNumber, columnNumber, length, line); }
Example 5
Source File: Resolver.java From DesigniteJava with Apache License 2.0 | 5 votes |
public List<SM_Type> inferStaticAccess(List<Name> staticFieldAccesses, SM_Type type) { List<SM_Type> typesOfStaticAccesses = new ArrayList<>(); for (Name typeName : staticFieldAccesses) { if (typeName.resolveBinding() instanceof ITypeBinding) { ITypeBinding iType = (ITypeBinding) typeName.resolveBinding(); if (iType != null && iType.getPackage() != null) { SM_Package sm_pkg = findPackage(iType.getPackage().getName().toString(), type.getParentPkg().getParentProject()); if (sm_pkg != null) { SM_Type sm_type = findType(iType.getName().toString(), sm_pkg); if (sm_type != null) { if (!typesOfStaticAccesses.contains(sm_type)) { typesOfStaticAccesses.add(sm_type); } } } } } else { String unresolvedTypeName = typeName.toString().replace("[]", ""); // cover the Array case SM_Type matchedType = manualLookupForUnresolvedType(type.getParentPkg().getParentProject(), unresolvedTypeName, type); if (matchedType != null) { if (!typesOfStaticAccesses.contains(matchedType)) { typesOfStaticAccesses.add(matchedType); } } } } return typesOfStaticAccesses; }
Example 6
Source File: Resolver.java From DesigniteJava with Apache License 2.0 | 5 votes |
public SM_Type resolveType(Type type, SM_Project project) { ITypeBinding binding = type.resolveBinding(); if (binding == null || binding.getPackage() == null) // instanceof String[] returns null package return null; SM_Package pkg = findPackage(binding.getPackage().getName(), project); if (pkg != null) { return findType(binding.getName(), pkg); } return null; }
Example 7
Source File: OverrideMethodsOperation.java From eclipse.jdt.ls with Eclipse Public License 2.0 | 5 votes |
public static List<OverridableMethod> listOverridableMethods(IType type) { if (type == null || type.getCompilationUnit() == null) { return Collections.emptyList(); } List<OverridableMethod> overridables = new ArrayList<>(); RefactoringASTParser astParser = new RefactoringASTParser(IASTSharedValues.SHARED_AST_LEVEL); CompilationUnit astRoot = astParser.parse(type.getCompilationUnit(), true); try { ITypeBinding typeBinding = ASTNodes.getTypeBinding(astRoot, type); if (typeBinding == null) { return overridables; } IMethodBinding cloneMethod = null; ITypeBinding cloneable = astRoot.getAST().resolveWellKnownType("java.lang.Cloneable"); if (Bindings.isSuperType(cloneable, typeBinding)) { cloneMethod = resolveWellKnownCloneMethod(astRoot.getAST()); } IPackageBinding pack = typeBinding.getPackage(); IMethodBinding[] methods = StubUtility2Core.getOverridableMethods(astRoot.getAST(), typeBinding, false); for (IMethodBinding method : methods) { if (Bindings.isVisibleInHierarchy(method, pack)) { boolean toImplement = Objects.equals(method, cloneMethod); overridables.add(convertToSerializableMethod(method, toImplement)); } } } catch (JavaModelException e) { JavaLanguageServerPlugin.logException("List overridable methods", e); } return overridables; }
Example 8
Source File: InJavaImporter.java From jdt2famix with Eclipse Public License 1.0 | 5 votes |
private ContainerEntity ensureContainerEntityForTypeBinding(ITypeBinding binding) { if (binding.getDeclaringClass() != null) return ensureTypeFromTypeBinding(binding.getDeclaringClass()); if (binding.getPackage() != null) return ensureNamespaceFromPackageBinding(binding.getPackage()); return unknownNamespace(); }
Example 9
Source File: Bindings.java From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 | 5 votes |
public static boolean isVisibleInHierarchy(IMethodBinding member, IPackageBinding pack) { int otherflags= member.getModifiers(); ITypeBinding declaringType= member.getDeclaringClass(); if (Modifier.isPublic(otherflags) || Modifier.isProtected(otherflags) || (declaringType != null && declaringType.isInterface())) { return true; } else if (Modifier.isPrivate(otherflags)) { return false; } return declaringType != null && pack == declaringType.getPackage(); }
Example 10
Source File: JdtUtils.java From j2cl with Apache License 2.0 | 4 votes |
public static TypeDeclaration createDeclarationForType(final ITypeBinding typeBinding) { if (typeBinding == null) { return null; } checkArgument(typeBinding.getTypeDeclaration() == typeBinding); checkArgument(!typeBinding.isArray()); checkArgument(!typeBinding.isParameterizedType()); checkArgument(!typeBinding.isTypeVariable()); checkArgument(!typeBinding.isWildcardType()); checkArgument(!typeBinding.isCapture()); PackageInfoCache packageInfoCache = PackageInfoCache.get(); ITypeBinding topLevelTypeBinding = toTopLevelTypeBinding(typeBinding); if (topLevelTypeBinding.isFromSource()) { // Let the PackageInfoCache know that this class is Source, otherwise it would have to rummage // around in the class path to figure it out and it might even come up with the wrong answer // for example if this class has also been globbed into some other library that is a // dependency of this one. PackageInfoCache.get().markAsSource(getBinaryNameFromTypeBinding(topLevelTypeBinding)); } // Compute these first since they're reused in other calculations. String packageName = typeBinding.getPackage() == null ? null : typeBinding.getPackage().getName(); boolean isAbstract = isAbstract(typeBinding); boolean isFinal = isFinal(typeBinding); Supplier<ImmutableMap<String, MethodDescriptor>> declaredMethods = () -> { ImmutableMap.Builder<String, MethodDescriptor> mapBuilder = ImmutableMap.builder(); for (IMethodBinding methodBinding : typeBinding.getDeclaredMethods()) { MethodDescriptor methodDescriptor = createMethodDescriptor(methodBinding); mapBuilder.put( // TODO(b/33595109): Using the method declaration signature here is kind of iffy; // but needs to be done because parameterized types might make multiple // superinterface methods collide which are represented by JDT as different method // bindings but with the same signature, e.g. // interface I<U, V extends Serializable> { // void foo(U u); // void foo(V v); // } // When considering the type I<A,A>, there are two different method bindings // that describe the single method 'void foo(A a)' each with the respective // method declaration. methodDescriptor.getDeclarationDescriptor().getMethodSignature(), methodDescriptor); } return mapBuilder.build(); }; Supplier<ImmutableList<FieldDescriptor>> declaredFields = () -> Arrays.stream(typeBinding.getDeclaredFields()) .map(JdtUtils::createFieldDescriptor) .collect(toImmutableList()); JsEnumInfo jsEnumInfo = JsInteropUtils.getJsEnumInfo(typeBinding); return TypeDeclaration.newBuilder() .setClassComponents(getClassComponents(typeBinding)) .setEnclosingTypeDeclaration(createDeclarationForType(typeBinding.getDeclaringClass())) .setInterfaceTypeDescriptorsFactory( () -> createTypeDescriptors(typeBinding.getInterfaces(), DeclaredTypeDescriptor.class)) .setUnparameterizedTypeDescriptorFactory(() -> createDeclaredTypeDescriptor(typeBinding)) .setHasAbstractModifier(isAbstract) .setKind(getKindFromTypeBinding(typeBinding)) .setCapturingEnclosingInstance(capturesEnclosingInstance(typeBinding)) .setFinal(isFinal) .setFunctionalInterface(typeBinding.getFunctionalInterfaceMethod() != null) .setJsFunctionInterface(JsInteropUtils.isJsFunction(typeBinding)) .setAnnotatedWithFunctionalInterface(isAnnotatedWithFunctionalInterface(typeBinding)) .setAnnotatedWithAutoValue(isAnnotatedWithAutoValue(typeBinding)) .setJsType(JsInteropUtils.isJsType(typeBinding)) .setJsEnumInfo(jsEnumInfo) .setNative(JsInteropUtils.isJsNativeType(typeBinding)) .setAnonymous(typeBinding.isAnonymous()) .setLocal(isLocal(typeBinding)) .setSimpleJsName(getJsName(typeBinding)) .setCustomizedJsNamespace(getJsNamespace(typeBinding, packageInfoCache)) .setPackageName(packageName) .setSuperTypeDescriptorFactory(getSuperTypeFactory(jsEnumInfo != null, typeBinding)) .setTypeParameterDescriptors( getTypeArgumentTypeDescriptors(typeBinding, TypeVariable.class)) .setVisibility(getVisibility(typeBinding)) .setDeclaredMethodDescriptorsFactory(declaredMethods) .setDeclaredFieldDescriptorsFactory(declaredFields) .setUnusableByJsSuppressed(JsInteropAnnotationUtils.isUnusableByJsSuppressed(typeBinding)) .setDeprecated(isDeprecated(typeBinding)) .build(); }
Example 11
Source File: ExtractClassRefactoring.java From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 | 4 votes |
private FieldDeclaration performFieldRewrite(IType type, ParameterObjectFactory pof, RefactoringStatus status) throws CoreException { fBaseCURewrite= new CompilationUnitRewrite(type.getCompilationUnit()); SimpleName name= (SimpleName) NodeFinder.perform(fBaseCURewrite.getRoot(), type.getNameRange()); TypeDeclaration typeNode= (TypeDeclaration) ASTNodes.getParent(name, ASTNode.TYPE_DECLARATION); ASTRewrite rewrite= fBaseCURewrite.getASTRewrite(); int modifier= Modifier.PRIVATE; TextEditGroup removeFieldGroup= fBaseCURewrite.createGroupDescription(RefactoringCoreMessages.ExtractClassRefactoring_group_remove_field); FieldDeclaration lastField= null; initializeDeclaration(typeNode); for (Iterator<FieldInfo> iter= fVariables.values().iterator(); iter.hasNext();) { FieldInfo pi= iter.next(); if (isCreateField(pi)) { VariableDeclarationFragment vdf= pi.declaration; FieldDeclaration parent= (FieldDeclaration) vdf.getParent(); if (lastField == null) lastField= parent; else if (lastField.getStartPosition() < parent.getStartPosition()) lastField= parent; ListRewrite listRewrite= rewrite.getListRewrite(parent, FieldDeclaration.FRAGMENTS_PROPERTY); removeNode(vdf, removeFieldGroup, fBaseCURewrite); if (listRewrite.getRewrittenList().size() == 0) { removeNode(parent, removeFieldGroup, fBaseCURewrite); } if (fDescriptor.isCreateTopLevel()) { IVariableBinding binding= vdf.resolveBinding(); ITypeRoot typeRoot= fBaseCURewrite.getCu(); if (binding == null || binding.getType() == null){ status.addFatalError(Messages.format(RefactoringCoreMessages.ExtractClassRefactoring_fatal_error_cannot_resolve_binding, BasicElementLabels.getJavaElementName(pi.name)), JavaStatusContext.create(typeRoot, vdf)); } else { ITypeBinding typeBinding= binding.getType(); if (Modifier.isPrivate(typeBinding.getModifiers())){ status.addError(Messages.format(RefactoringCoreMessages.ExtractClassRefactoring_error_referencing_private_class, BasicElementLabels.getJavaElementName(typeBinding.getName())), JavaStatusContext.create(typeRoot, vdf)); } else if (Modifier.isProtected(typeBinding.getModifiers())){ ITypeBinding declaringClass= typeBinding.getDeclaringClass(); if (declaringClass != null) { IPackageBinding package1= declaringClass.getPackage(); if (package1 != null && !fDescriptor.getPackage().equals(package1.getName())){ status.addError(Messages.format(RefactoringCoreMessages.ExtractClassRefactoring_error_referencing_protected_class, new String[] {BasicElementLabels.getJavaElementName(typeBinding.getName()), BasicElementLabels.getJavaElementName(fDescriptor.getPackage())}), JavaStatusContext.create(typeRoot, vdf)); } } } } } Expression initializer= vdf.getInitializer(); if (initializer != null) pi.initializer= initializer; int modifiers= parent.getModifiers(); if (!MemberVisibilityAdjustor.hasLowerVisibility(modifiers, modifier)){ modifier= modifiers; } } } FieldDeclaration fieldDeclaration= createParameterObjectField(pof, typeNode, modifier); ListRewrite bodyDeclList= rewrite.getListRewrite(typeNode, TypeDeclaration.BODY_DECLARATIONS_PROPERTY); if (lastField != null) bodyDeclList.insertAfter(fieldDeclaration, lastField, null); else bodyDeclList.insertFirst(fieldDeclaration, null); return fieldDeclaration; }
Example 12
Source File: StubUtility2.java From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 | 4 votes |
public static MethodDeclaration createDelegationStub(ICompilationUnit unit, ASTRewrite rewrite, ImportRewrite imports, ImportRewriteContext context, IMethodBinding delegate, IVariableBinding delegatingField, CodeGenerationSettings settings) throws CoreException { Assert.isNotNull(delegate); Assert.isNotNull(delegatingField); Assert.isNotNull(settings); AST ast= rewrite.getAST(); MethodDeclaration decl= ast.newMethodDeclaration(); decl.modifiers().addAll(ASTNodeFactory.newModifiers(ast, delegate.getModifiers() & ~Modifier.SYNCHRONIZED & ~Modifier.ABSTRACT & ~Modifier.NATIVE)); decl.setName(ast.newSimpleName(delegate.getName())); decl.setConstructor(false); createTypeParameters(imports, context, ast, delegate, decl); decl.setReturnType2(imports.addImport(delegate.getReturnType(), ast, context)); List<SingleVariableDeclaration> params= createParameters(unit.getJavaProject(), imports, context, ast, delegate, null, decl); createThrownExceptions(decl, delegate, imports, context, ast); Block body= ast.newBlock(); decl.setBody(body); String delimiter= StubUtility.getLineDelimiterUsed(unit); Statement statement= null; MethodInvocation invocation= ast.newMethodInvocation(); invocation.setName(ast.newSimpleName(delegate.getName())); List<Expression> arguments= invocation.arguments(); for (int i= 0; i < params.size(); i++) arguments.add(ast.newSimpleName(params.get(i).getName().getIdentifier())); if (settings.useKeywordThis) { FieldAccess access= ast.newFieldAccess(); access.setExpression(ast.newThisExpression()); access.setName(ast.newSimpleName(delegatingField.getName())); invocation.setExpression(access); } else invocation.setExpression(ast.newSimpleName(delegatingField.getName())); if (delegate.getReturnType().isPrimitive() && delegate.getReturnType().getName().equals("void")) {//$NON-NLS-1$ statement= ast.newExpressionStatement(invocation); } else { ReturnStatement returnStatement= ast.newReturnStatement(); returnStatement.setExpression(invocation); statement= returnStatement; } body.statements().add(statement); ITypeBinding declaringType= delegatingField.getDeclaringClass(); if (declaringType == null) { // can be null for return decl; } String qualifiedName= declaringType.getQualifiedName(); IPackageBinding packageBinding= declaringType.getPackage(); if (packageBinding != null) { if (packageBinding.getName().length() > 0 && qualifiedName.startsWith(packageBinding.getName())) qualifiedName= qualifiedName.substring(packageBinding.getName().length()); } if (settings.createComments) { /* * TODO: have API for delegate method comments This is an inlined * version of * {@link CodeGeneration#getMethodComment(ICompilationUnit, String, MethodDeclaration, IMethodBinding, String)} */ delegate= delegate.getMethodDeclaration(); String declaringClassQualifiedName= delegate.getDeclaringClass().getQualifiedName(); String linkToMethodName= delegate.getName(); String[] parameterTypesQualifiedNames= StubUtility.getParameterTypeNamesForSeeTag(delegate); String string= StubUtility.getMethodComment(unit, qualifiedName, decl, delegate.isDeprecated(), linkToMethodName, declaringClassQualifiedName, parameterTypesQualifiedNames, true, delimiter); if (string != null) { Javadoc javadoc= (Javadoc) rewrite.createStringPlaceholder(string, ASTNode.JAVADOC); decl.setJavadoc(javadoc); } } return decl; }