public Type(IType type) { if (type == null) throw new IllegalArgumentException("Invalid argument: JDT Type is null"); this.type = type; packageName = type.getPackageFragment().getElementName(); IPackageFragmentRoot packageRoot = (IPackageFragmentRoot) type.getPackageFragment().getParent(); IFolder folder = (IFolder) packageRoot.getResource(); sourceFolder = folder.getName(); // sourceFolder = type.getfo }
/** * Determines if the supplied src file contains an import for the supplied type (including * wildcard .* imports). * * @param src The compilation unit. * @param type The type. * @return true if the src file has a qualifying import. */ public static boolean containsImport(ICompilationUnit src, IType type) throws Exception { String typePkg = type.getPackageFragment().getElementName(); IPackageDeclaration[] packages = src.getPackageDeclarations(); String pkg = packages.length > 0 ? packages[0].getElementName() : null; // classes in same package are auto imported. if ((pkg == null && typePkg == null) || (pkg != null && pkg.equals(typePkg))) { return true; } // java.lang is auto imported. if (JAVA_LANG.equals(typePkg)) { return true; } typePkg = typePkg + ".*"; String typeName = type.getFullyQualifiedName().replace('$', '.'); IImportDeclaration[] imports = src.getImports(); for (int ii = 0; ii < imports.length; ii++) { String name = imports[ii].getElementName(); if (name.equals(typeName) || name.equals(typePkg)) { return true; } } return false; }
public String getContainingPackageName() { IType containingType = getContainingType(); if (containingType == null) { return ""; } return containingType.getPackageFragment().getElementName(); }
private static void appendTypePath(IType type, StringBuffer buf) { IPackageFragment pack = type.getPackageFragment(); String packPath = pack.getElementName().replace('.', '/'); String typePath = type.getTypeQualifiedName('.'); if (packPath.length() > 0) { buf.append(packPath); buf.append('/'); } buf.append(typePath); buf.append(".html"); // $NON-NLS-1$ }
private void createModel() { // // Initialize m_classes // Set<String> packageSet = Sets.newHashSet(); List<IType> types = Utils.findTypes(Utils.getSelectedJavaElements(), Utils.CONVERSION_FILTER); for (IType type : types) { String packageName = type.getPackageFragment().getElementName(); String className = type.getElementName(); if (className != null) { XmlClass c = new XmlClass(packageName + "." + className, false /* don't resolve */); p("Adding class " + c); m_classes.add(c); packageSet.add(packageName); } else { p("Adding type " + type); m_classes.add(new XmlClass(type.getFullyQualifiedName(), false /* don't resolve */)); packageSet.add(packageName); } } // for (JavaElement element : m_selectedElements) { // if (element.getClassName() != null) { // XmlClass c = new XmlClass(element.getPackageName() + "." + element.getClassName(), // false /* don't resolve */); // p("Adding class " + c); // m_classes.add(c); // packageSet.add(element.getPackageName()); // } else { // for (IType type : types) { // p("Adding type " + type); // m_classes.add(new XmlClass(type.getFullyQualifiedName(), false /* don't resolve // */)); // packageSet.add(type.getPackageFragment().getElementName()); // } // } // } // // Initialize m_packages // for (String p : packageSet) { XmlPackage pkg = new XmlPackage(); pkg.setName(p); p("Adding package " + p); m_packages.add(pkg); } m_xmlSuite = createXmlSuite(); }
protected String packageNameForComponent(String componentName) { IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject(getContainerFullPath().segment(0)); try { LocalizedComponentsLocateResult result = LocatePlugin.getDefault().getLocalizedComponentsLocateResult(project, componentName); IType javaType; if (result != null && (javaType = result.getDotJavaType()) != null) { return javaType.getPackageFragment().getElementName(); } } catch (CoreException e) { e.printStackTrace(); } catch (LocateException e) { e.printStackTrace(); } return null; }
/** @see IJavaElementRequestor */ public void acceptType(IType type) { try { if (this.unitToSkip != null && this.unitToSkip.equals(type.getCompilationUnit())) { return; } char[] packageName = type.getPackageFragment().getElementName().toCharArray(); boolean isBinary = type instanceof BinaryType; // determine associated access restriction AccessRestriction accessRestriction = null; if (this.checkAccessRestrictions && (isBinary || !type.getJavaProject().equals(this.project))) { PackageFragmentRoot root = (PackageFragmentRoot) type.getAncestor(IJavaElement.PACKAGE_FRAGMENT_ROOT); ClasspathEntry entry = (ClasspathEntry) this.nameLookup.rootToResolvedEntries.get(root); if (entry != null) { // reverse map always contains resolved CP entry AccessRuleSet accessRuleSet = entry.getAccessRuleSet(); if (accessRuleSet != null) { // TODO (philippe) improve char[] <-> String conversions to avoid performing them on the // fly char[][] packageChars = CharOperation.splitOn('.', packageName); char[] fileWithoutExtension = type.getElementName().toCharArray(); accessRestriction = accessRuleSet.getViolatedRestriction( CharOperation.concatWith(packageChars, fileWithoutExtension, '/')); } } } this.requestor.acceptType( packageName, type.getElementName().toCharArray(), null, type.getFlags(), accessRestriction); } catch (JavaModelException jme) { // ignore } }
protected void browseForAccessorClass() { IProgressService service = PlatformUI.getWorkbench().getProgressService(); IPackageFragmentRoot root = fAccessorPackage.getSelectedFragmentRoot(); IJavaSearchScope scope = root != null ? SearchEngine.createJavaSearchScope(new IJavaElement[] {root}) : SearchEngine.createWorkspaceScope(); FilteredTypesSelectionDialog dialog = new FilteredTypesSelectionDialog( getShell(), false, service, scope, IJavaSearchConstants.CLASS); dialog.setTitle(NLSUIMessages.NLSAccessorConfigurationDialog_Accessor_Selection); dialog.setMessage(NLSUIMessages.NLSAccessorConfigurationDialog_Choose_the_accessor_file); dialog.setInitialPattern("*Messages"); // $NON-NLS-1$ if (dialog.open() == Window.OK) { IType selectedType = (IType) dialog.getFirstResult(); if (selectedType != null) { fAccessorClassName.setText(selectedType.getElementName()); fAccessorPackage.setSelected(selectedType.getPackageFragment()); } } }
private void buildForProject( JavaProject project, ArrayList potentialSubtypes, org.eclipse.jdt.core.ICompilationUnit[] workingCopies, HashSet localTypes, IProgressMonitor monitor) throws JavaModelException { // resolve int openablesLength = potentialSubtypes.size(); if (openablesLength > 0) { // copy vectors into arrays Openable[] openables = new Openable[openablesLength]; potentialSubtypes.toArray(openables); // sort in the order of roots and in reverse alphabetical order for .class file // since requesting top level types in the process of caching an enclosing type is // not supported by the lookup environment IPackageFragmentRoot[] roots = project.getPackageFragmentRoots(); int rootsLength = roots.length; final HashtableOfObjectToInt indexes = new HashtableOfObjectToInt(openablesLength); for (int i = 0; i < openablesLength; i++) { IJavaElement root = openables[i].getAncestor(IJavaElement.PACKAGE_FRAGMENT_ROOT); int index; for (index = 0; index < rootsLength; index++) { if (roots[index].equals(root)) break; } indexes.put(openables[i], index); } Arrays.sort( openables, new Comparator() { public int compare(Object a, Object b) { int aIndex = indexes.get(a); int bIndex = indexes.get(b); if (aIndex != bIndex) return aIndex - bIndex; return ((Openable) b).getElementName().compareTo(((Openable) a).getElementName()); } }); IType focusType = getType(); boolean inProjectOfFocusType = focusType != null && focusType.getJavaProject().equals(project); org.eclipse.jdt.core.ICompilationUnit[] unitsToLookInside = null; if (inProjectOfFocusType) { org.eclipse.jdt.core.ICompilationUnit unitToLookInside = focusType.getCompilationUnit(); if (unitToLookInside != null) { int wcLength = workingCopies == null ? 0 : workingCopies.length; if (wcLength == 0) { unitsToLookInside = new org.eclipse.jdt.core.ICompilationUnit[] {unitToLookInside}; } else { unitsToLookInside = new org.eclipse.jdt.core.ICompilationUnit[wcLength + 1]; unitsToLookInside[0] = unitToLookInside; System.arraycopy(workingCopies, 0, unitsToLookInside, 1, wcLength); } } else { unitsToLookInside = workingCopies; } } SearchableEnvironment searchableEnvironment = project.newSearchableNameEnvironment(unitsToLookInside); this.nameLookup = searchableEnvironment.nameLookup; Map options = project.getOptions(true); // disable task tags to speed up parsing options.put(JavaCore.COMPILER_TASK_TAGS, ""); // $NON-NLS-1$ this.hierarchyResolver = new HierarchyResolver(searchableEnvironment, options, this, new DefaultProblemFactory()); if (focusType != null) { Member declaringMember = ((Member) focusType).getOuterMostLocalContext(); if (declaringMember == null) { // top level or member type if (!inProjectOfFocusType) { char[] typeQualifiedName = focusType.getTypeQualifiedName('.').toCharArray(); String[] packageName = ((PackageFragment) focusType.getPackageFragment()).names; if (searchableEnvironment.findType(typeQualifiedName, Util.toCharArrays(packageName)) == null) { // focus type is not visible in this project: no need to go further return; } } } else { // local or anonymous type Openable openable; if (declaringMember.isBinary()) { openable = (Openable) declaringMember.getClassFile(); } else { openable = (Openable) declaringMember.getCompilationUnit(); } localTypes = new HashSet(); localTypes.add(openable.getPath().toString()); this.hierarchyResolver.resolve(new Openable[] {openable}, localTypes, monitor); return; } } this.hierarchyResolver.resolve(openables, localTypes, monitor); } }
/** * Resolves a type name in the context of the declaring type. * * @param refTypeSig the type name in signature notation (for example 'QVector') this can also * be an array type, but dimensions will be ignored. * @param declaringType the context for resolving (type where the reference was made in) * @return returns the fully qualified type name or build-in-type name. if a unresolved type * couldn't be resolved null is returned * @throws JavaModelException thrown when the type can not be accessed */ public IType resolveType(String refTypeSig, IType declaringType) throws JavaModelException { IJavaProject javaProject = declaringType.getJavaProject(); int arrayCount = Signature.getArrayCount(refTypeSig); char type = refTypeSig.charAt(arrayCount); if (type == Signature.C_UNRESOLVED) { String name = ""; // $NON-NLS-1$ int bracket = refTypeSig.indexOf(Signature.C_GENERIC_START, arrayCount + 1); if (bracket > 0) name = refTypeSig.substring(arrayCount + 1, bracket); else { int semi = refTypeSig.indexOf(Signature.C_SEMICOLON, arrayCount + 1); if (semi == -1) { throw new IllegalArgumentException(); } name = refTypeSig.substring(arrayCount + 1, semi); } String dotTypeName = "." + name; String dotBaseTypeName = null; String dotExtensionTypeName = null; int dotIndex = name.indexOf('.'); if (dotIndex != -1) { // We might get a fully qualified type name -- Qcom.apple.jingle.eo.MZProgramNodeType; IType resolvedType = javaProject.findType(name); if (resolvedType != null) { return resolvedType; } // If not, then this might be a nested type reference on another type, so let's split it // to look for that in our imports later dotBaseTypeName = "." + name.substring(0, dotIndex); dotExtensionTypeName = name.substring(dotIndex); } IImportDeclaration[] importDeclarations = declaringType.getCompilationUnit().getImports(); // Loop over the imports and look for the import of our symbol for (IImportDeclaration declaration : importDeclarations) { String importName = declaration.getElementName(); // If it's a .* import, then pop off the package name and lookup the type if (declaration.isOnDemand()) { String packageName = importName.substring(0, importName.lastIndexOf('.')); String possibleTypeName = packageName + dotTypeName; IType onDemandPackageType = javaProject.findType(possibleTypeName); if (onDemandPackageType != null) { return onDemandPackageType; } } // If it's not a .* import, then does the import end with our type name? else if (importName.endsWith(dotTypeName)) { IType importType = javaProject.findType(importName); if (importType != null) { return importType; } } // If it doesn't, check to see if we were a dotted type ("Outer.Inner") and check to see // if Outer is imported else if (dotBaseTypeName != null && importName.endsWith(dotBaseTypeName)) { // ... then look for Outer.Inner IType importNestedType = javaProject.findType(importName + dotExtensionTypeName); if (importNestedType != null) { return importNestedType; } } } // Is this a java.lang.Xxx class that we get for free? String javaLangTypeName = "java.lang" + dotTypeName; IType javaLangType = javaProject.findType(javaLangTypeName); if (javaLangType != null) { return javaLangType; } // What about an inner type of our own class? String innerTypeName = declaringType.getFullyQualifiedName('.') + dotTypeName; IType innerType = javaProject.findType(innerTypeName); if (innerType != null) { return innerType; } // Are we declared in a package? IPackageFragment declaringTypePackageFragment = declaringType.getPackageFragment(); if (declaringTypePackageFragment != null) { // ... if so, is this name in our package, so it didn't need an import? String samePackageTypeName = declaringTypePackageFragment.getElementName() + dotTypeName; IType samePackageType = javaProject.findType(samePackageTypeName); if (samePackageType != null) { return samePackageType; } } else { // If we were in the default package, is that class in the default package too? IType defaultPackageType = javaProject.findType(name); if (defaultPackageType != null) { return defaultPackageType; } } String slowResolvedTypeName = JavaModelUtil.getResolvedTypeName(refTypeSig, _type); if (slowResolvedTypeName != null) { IType slowResolvedType = javaProject.findType(slowResolvedTypeName); if (slowResolvedType != null) { return slowResolvedType; } } return null; } else { // We were given an Lxxx; signature ... just look it up String resolvedTypeName = Signature.toString(refTypeSig.substring(arrayCount)); IType resolvedType = javaProject.findType(resolvedTypeName); return resolvedType; } }
/** * Creates a qualified class name from a class name which doesn't contain package name. * * @param parent a full qualified class name of the class which uses this variable * @param type a class name which doesn't contain package name * @return full a created qualified class name */ public static String getFullQName(IType parent, String type) { if (type.indexOf('.') >= 0) { return type; } if (isPrimitive(type)) { return type; } IJavaProject project = parent.getJavaProject(); try { IType javaType = project.findType("java.lang." + type); if (javaType != null && javaType.exists()) { return javaType.getFullyQualifiedName(); } } catch (Exception ex) { ex.printStackTrace(); } while (true) { try { IType javaType = project.findType(parent.getFullyQualifiedName() + "." + type); if (javaType != null && javaType.exists()) { return parent.getFullyQualifiedName() + "." + type; } } catch (Exception ex) { ex.printStackTrace(); } try { IType javaType = project.findType(parent.getPackageFragment().getElementName() + "." + type); if (javaType != null && javaType.exists()) { return javaType.getFullyQualifiedName(); } } catch (Exception ex) { ex.printStackTrace(); } try { IImportDeclaration[] imports = parent.getCompilationUnit().getImports(); for (int i = 0; i < imports.length; i++) { String importName = imports[i].getElementName(); if (importName.endsWith("." + type)) { return importName; } if (importName.endsWith(".*")) { try { IType javaType = project.findType(importName.replaceFirst("\\*$", type)); if (javaType != null && javaType.exists()) { return javaType.getFullyQualifiedName(); } } catch (Exception ex) { } } } } catch (Exception ex) { ex.printStackTrace(); } try { // スーパークラス if (parent.getSuperclassTypeSignature() == null) { break; } String superClass = JavaUtil.getFullQName(parent, Signature.toString(parent.getSuperclassTypeSignature())); if (superClass.startsWith("java.lang.")) { break; } parent = parent.getJavaProject().findType(superClass); } catch (JavaModelException ex) { } } return type; }
public static String resolveClassName(String className, IType type) { if (className == null || type == null) { return className; } // replace binary $ inner class name syntax with . for source level className = className.replace('$', '.'); String dotClassName = new StringBuilder().append('.').append(className).toString(); IProject project = type.getJavaProject().getProject(); try { // Special handling for some well-know classes if (className.startsWith("java.lang") && getJavaType(project, className) != null) { return className; } // Check if the class is imported if (!type.isBinary()) { // Strip className to first segment to support ReflectionUtils.MethodCallback int ix = className.lastIndexOf('.'); String firstClassNameSegment = className; if (ix > 0) { firstClassNameSegment = className.substring(0, ix); } // Iterate the imports for (IImportDeclaration importDeclaration : type.getCompilationUnit().getImports()) { String importName = importDeclaration.getElementName(); // Wildcard imports -> check if the package + className is a valid type if (importDeclaration.isOnDemand()) { String newClassName = new StringBuilder(importName.substring(0, importName.length() - 1)) .append(className) .toString(); if (getJavaType(project, newClassName) != null) { return newClassName; } } // Concrete import matching .className at the end -> check if type exists else if (importName.endsWith(dotClassName) && getJavaType(project, importName) != null) { return importName; } // Check if className is multi segmented (ReflectionUtils.MethodCallback) // -> check if the first segment else if (!className.equals(firstClassNameSegment)) { if (importName.endsWith(firstClassNameSegment)) { String newClassName = new StringBuilder(importName.substring(0, importName.lastIndexOf('.') + 1)) .append(className) .toString(); if (getJavaType(project, newClassName) != null) { return newClassName; } } } } } // Check if the class is in the same package as the type String packageName = type.getPackageFragment().getElementName(); String newClassName = new StringBuilder(packageName).append(dotClassName).toString(); if (getJavaType(project, newClassName) != null) { return newClassName; } // Check if the className is sufficient (already fully-qualified) if (getJavaType(project, className) != null) { return className; } // Check if the class is coming from the java.lang newClassName = new StringBuilder("java.lang").append(dotClassName).toString(); if (getJavaType(project, newClassName) != null) { return newClassName; } // Fall back to full blown resolution String[][] fullInter = type.resolveType(className); if (fullInter != null && fullInter.length > 0) { return fullInter[0][0] + "." + fullInter[0][1]; } } catch (JavaModelException e) { SpringCore.log(e); } return className; }