org.eclipse.jdt.core.IType Java Examples

The following examples show how to use org.eclipse.jdt.core.IType. 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: AbstractXbaseContentAssistTest.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
protected static void doInitBigDecimalFeatures(IJavaProject javaProject) throws JavaModelException {
	IType bigDecimalType = javaProject.findType(BigDecimal.class.getName());
	Set<String> featuresOrTypes = Sets.newHashSet();
	List<String> features = Lists.newArrayList();
	List<String> staticFeatures = Lists.newArrayList();
	addMethods(bigDecimalType, features, staticFeatures, featuresOrTypes);
	// compareTo(T) is actually overridden by compareTo(String) but contained twice in String.class#getMethods
	features.remove("compareTo()");
	Set<String> featuresAsSet = Sets.newHashSet(features);
	Set<String> staticFeaturesAsSet = Sets.newHashSet(staticFeatures);
	Set<String> types = Sets.newHashSet();
	addFields(bigDecimalType, features, staticFeatures, featuresAsSet, staticFeaturesAsSet, types);
	// Object extensions
	features.add("identityEquals()");
	BIGDECIMAL_FEATURES = features.toArray(new String[features.size()]);
	STATIC_BIGDECIMAL_FEATURES = staticFeatures.toArray(new String[staticFeatures.size()]);
}
 
Example #2
Source File: AbstractHierarchyViewerSorter.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private IType getDefiningType(IMethod method) throws JavaModelException {
	int flags= method.getFlags();
	if (Flags.isPrivate(flags) || Flags.isStatic(flags) || method.isConstructor()) {
		return null;
	}

	IType declaringType= method.getDeclaringType();
	ITypeHierarchy hierarchy= getHierarchy(declaringType);
	if (hierarchy != null) {
		MethodOverrideTester tester= new MethodOverrideTester(declaringType, hierarchy);
		IMethod res= tester.findDeclaringMethod(method, true);
		if (res != null) {
			return res.getDeclaringType();
		}
	}
	return null;
}
 
Example #3
Source File: CompilationUnitCompletion.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Finds and returns the super type signature in the
 * <code>extends</code> or <code>implements</code> clause of
 * <code>subType</code> that corresponds to <code>superType</code>.
 *
 * @param subType a direct and true sub type of <code>superType</code>
 * @param superType a direct super type (super class or interface) of
 *        <code>subType</code>
 * @return the super type signature of <code>subType</code> referring
 *         to <code>superType</code>
 * @throws JavaModelException if extracting the super type signatures
 *         fails, or if <code>subType</code> contains no super type
 *         signature to <code>superType</code>
 */
private String findMatchingSuperTypeSignature(IType subType, IType superType) throws JavaModelException {
	String[] signatures= getSuperTypeSignatures(subType, superType);
	for (int i= 0; i < signatures.length; i++) {
		String signature= signatures[i];
		String qualified= SignatureUtil.qualifySignature(signature, subType);
		String subFQN= SignatureUtil.stripSignatureToFQN(qualified);

		String superFQN= superType.getFullyQualifiedName();
		if (subFQN.equals(superFQN)) {
			return signature;
		}

		// handle local types
		if (fLocalTypes.containsValue(subFQN)) {
			return signature;
		}
	}

	throw new JavaModelException(new CoreException(new Status(IStatus.ERROR, JavaPlugin.getPluginId(), IStatus.OK, "Illegal hierarchy", null))); //$NON-NLS-1$
}
 
Example #4
Source File: GWTDeleteCompilationUnitParticipantTest.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 6 votes vote down vote up
public void testCreateChange() throws OperationCanceledException,
    CoreException {
  // We're going to delete compilation unit R.java
  ICompilationUnit cu = rClass.getCompilationUnit();
  IType r = cu.getType("R");

  // Verify that the index currently contains one JSNI reference to R
  Set<IIndexedJavaRef> refs = JavaRefIndex.getInstance().findTypeReferences(
      r.getFullyQualifiedName());
  assertEquals(1, refs.size());

  // Delete R.java
  cu.delete(true, null);
  assertFalse(cu.exists());

  // Now verify that the index entries pointing to R have been purged
  refs = JavaRefIndex.getInstance().findTypeReferences(r.getElementName());
  assertEquals(0, refs.size());
}
 
Example #5
Source File: JavaElementLinks.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
private static IType resolveType(IType baseType, String refTypeName) throws JavaModelException {
	if (refTypeName.length() == 0) {
		return baseType;
	}

	String[][] resolvedNames = baseType.resolveType(refTypeName);
	if (resolvedNames != null && resolvedNames.length > 0) {
		return baseType.getJavaProject().findType(resolvedNames[0][0], resolvedNames[0][1].replace('$', '.'), (IProgressMonitor) null);

	} else if (baseType.isBinary()) {
		// workaround for https://bugs.eclipse.org/bugs/show_bug.cgi?id=206597
		IType type = baseType.getJavaProject().findType(refTypeName, (IProgressMonitor) null);
		if (type == null) {
			// could be unqualified reference:
			type = baseType.getJavaProject().findType(baseType.getPackageFragment().getElementName() + '.' + refTypeName, (IProgressMonitor) null);
		}
		return type;

	} else {
		return null;
	}
}
 
Example #6
Source File: Implementors.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Searches for interfaces which are implemented by the declaring classes of the
 * specified Java elements. Currently, only IMethod instances are searched for.
 * Also, only the first element of the elements parameter is taken into
 * consideration.
 *
 * @param elements
 *
 * @return An array of found interfaces implemented by the declaring classes of the
 *         specified Java elements (currently only IMethod instances)
 */
public IJavaElement[] searchForInterfaces(IJavaElement[] elements,
    IProgressMonitor progressMonitor) {
    if ((elements != null) && (elements.length > 0)) {
        IJavaElement element = elements[0];

        if (element instanceof IMember) {
            IMember member = (IMember) element;
            IType type = member.getDeclaringType();

            IType[] implementingTypes = findInterfaces(type, progressMonitor);

            if (!progressMonitor.isCanceled()) {
                if (member.getElementType() == IJavaElement.METHOD) {
                    return findMethods((IMethod)member, implementingTypes, progressMonitor);
                } else {
                    return implementingTypes;
                }
            }
        }
    }

    return null;
}
 
Example #7
Source File: PullUpRefactoringProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private RefactoringStatus checkAccessedTypes(final IProgressMonitor monitor, final ITypeHierarchy hierarchy) throws JavaModelException {
	final RefactoringStatus result= new RefactoringStatus();
	final IType[] accessedTypes= getTypesReferencedInMovedMembers(monitor);
	final IType destination= getDestinationType();
	final List<IMember> pulledUpList= Arrays.asList(fMembersToMove);
	for (int index= 0; index < accessedTypes.length; index++) {
		final IType type= accessedTypes[index];
		if (!type.exists())
			continue;

		if (!canBeAccessedFrom(type, destination, hierarchy) && !pulledUpList.contains(type)) {
			final String message= Messages.format(RefactoringCoreMessages.PullUpRefactoring_type_not_accessible, new String[] { JavaElementLabels.getTextLabel(type, JavaElementLabels.ALL_FULLY_QUALIFIED), JavaElementLabels.getTextLabel(destination, JavaElementLabels.ALL_FULLY_QUALIFIED)});
			result.addError(message, JavaStatusContext.create(type));
		}
	}
	monitor.done();
	return result;
}
 
Example #8
Source File: DetectImplHyperlinksTest.java    From xtext-xtend with Eclipse Public License 2.0 6 votes vote down vote up
@Test public void testComputeHyperlink_1() throws Exception {
	String content = "package foo class Foo { def b|ar(String a) {} }";
	XtextEditor xtextEditor = openEditor(content.replace("|", ""));
	int offset = content.indexOf("|");

	IHyperlink[] detectHyperlinks = hyperlinkDetector.detectHyperlinks(xtextEditor.getInternalSourceViewer(), new Region(offset,1), true);
	assertEquals(2, detectHyperlinks.length);
	IHyperlink hyperlink = detectHyperlinks[0];
	assertTrue(hyperlink instanceof JdtHyperlink);
	JdtHyperlink casted = (JdtHyperlink) hyperlink;
	assertEquals(offset -1, casted.getHyperlinkRegion().getOffset());
	assertEquals(3, casted.getHyperlinkRegion().getLength());
	IJavaElement element = ((JdtHyperlink) hyperlink).getJavaElement();
	assertTrue(element instanceof IType);
	assertEquals("Object", element.getElementName());
	assertEquals("Open Inferred Type - Object", casted.getHyperlinkText());
}
 
Example #9
Source File: JavaSetterOperatorConstraintTest.java    From bonita-studio with GNU General Public License v2.0 6 votes vote down vote up
@Test
public void should_fail_if_setter_method_doesnt_exist_in_left_variable_class() throws Exception {
    final JavaSetterOperatorConstraint constraint = createConstraint();
    final IType employeeType = typeWithMethods(constraint, aPublicMethod("setChecked", Boolean.class.getName()));
    doReturn(employeeType).when(javaProject).findType("com.test.Employee");

    final IValidationContext aValidationContext = aValidationContext(anOperator()
            .withType(ExpressionConstants.JAVA_METHOD_OPERATOR)
            .withExpression("setIsChecked")
            .havingInputTypes(Boolean.class.getName())
            .in(anOperation().havingLeftOperand(anExpression().withName("myEmployee").withReturnType("com.test.Employee")))
            .build());
    constraint.performBatchValidation(aValidationContext);

    verify(aValidationContext).createFailureStatus(
            NLS.bind(Messages.methodDoesnotExistInLeftOperandType, new String[] { "setIsChecked", Boolean.class.getName(),
                    "myEmployee" }));
}
 
Example #10
Source File: JDTMethodHelper.java    From bonita-studio with GNU General Public License v2.0 6 votes vote down vote up
private static List<IField> getAllDeclaredFields(final IType type) throws JavaModelException {
    List<IField> fields = new ArrayList<>();
    fields.addAll(Arrays.asList(type.getFields()));
    ITypeHierarchy typeHierarchy = type.newSupertypeHierarchy(Repository.NULL_PROGRESS_MONITOR);
    Stream.of(typeHierarchy.getAllSuperclasses(type))
            .filter(t -> !Object.class.getName().equals(t.getElementName()))
            .filter(t -> isGroovySourceType(t))
            .flatMap(t -> {
                try {
                    return Stream.of(t.getFields());
                } catch (JavaModelException e) {
                    return Stream.empty();
                }
            })
            .forEach(fields::add);
    return fields;
}
 
Example #11
Source File: JavaTypeCompletionProposal.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Updates the replacement string.
 * 
 * @param document the document
 * @param trigger the trigger
 * @param offset the offset
 * @param impRewrite the import rewrite
 * @return <code>true</code> if the cursor position should be updated, <code>false</code> otherwise
 * @throws BadLocationException if accessing the document fails
 * @throws CoreException if something else fails
 */
protected boolean updateReplacementString(IDocument document, char trigger, int offset, ImportRewrite impRewrite) throws CoreException, BadLocationException {
	// avoid adding imports when inside imports container
	if (impRewrite != null && fFullyQualifiedTypeName != null) {
		String replacementString= getReplacementString();
		String qualifiedType= fFullyQualifiedTypeName;
		if (qualifiedType.indexOf('.') != -1 && replacementString.startsWith(qualifiedType) && !replacementString.endsWith(String.valueOf(';'))) {
			IType[] types= impRewrite.getCompilationUnit().getTypes();
			if (types.length > 0 && types[0].getSourceRange().getOffset() <= offset) {
				// ignore positions above type.
				setReplacementString(impRewrite.addImport(getReplacementString()));
				return true;
			}
		}
	}
	return false;
}
 
Example #12
Source File: MethodCallAnalyzer.java    From JDeodorant with MIT License 6 votes vote down vote up
private IType exactSubType(AbstractVariable variableDeclaration, Set<IType> subTypes) {
	if(variableDeclaration != null) {
		PlainVariable plainVariable = null;
		if(variableDeclaration instanceof PlainVariable) {
			plainVariable = (PlainVariable)variableDeclaration;
		}
		else if(variableDeclaration instanceof CompositeVariable) {
			plainVariable = ((CompositeVariable)variableDeclaration).getFinalVariable();
		}
		for(IType subType : subTypes) {
			if(plainVariable.getVariableType().startsWith(subType.getFullyQualifiedName())) {
				return subType;
			}
		}
	}
	return null;
}
 
Example #13
Source File: AbstractNewSarlElementWizardPage.java    From sarl with Apache License 2.0 6 votes vote down vote up
@Override
protected IType chooseSuperClass() {
	final IJavaProject project = getJavaProject();
	if (project == null) {
		return null;
	}
	final IJvmTypeProvider typeProvider = this.jdtTypeProviderFactory.findOrCreateTypeProvider(
			this.resourceSetFactory.get(project.getProject()));
	final SarlSpecificTypeSelectionExtension extension = new SarlSpecificTypeSelectionExtension(typeProvider);
	this.injector.injectMembers(extension);
	final AbstractSuperTypeSelectionDialog<?> dialog = createSuperClassSelectionDialog(getShell(),
			getWizard().getContainer(), project, extension, false);
	if (dialog == null) {
		return super.chooseSuperClass();
	}

	this.injector.injectMembers(dialog);
	dialog.setTitle(NewWizardMessages.NewTypeWizardPage_SuperClassDialog_title);
	dialog.setMessage(NewWizardMessages.NewTypeWizardPage_SuperClassDialog_message);
	dialog.setInitialPattern(getSuperClass());

	if (dialog.open() == Window.OK) {
		return (IType) dialog.getFirstResult();
	}
	return null;
}
 
Example #14
Source File: OpenSuperImplementationAction.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private boolean checkMethod(IMethod method) {
	try {
		int flags= method.getFlags();
		if (!Flags.isStatic(flags) && !Flags.isPrivate(flags)) {
			IType declaringType= method.getDeclaringType();
			if (SuperTypeHierarchyCache.hasInCache(declaringType)) {
				if (findSuperImplementation(method) == null) {
					return false;
				}
			}
			return true;
		}
	} catch (JavaModelException e) {
		if (!e.isDoesNotExist()) {
			JavaPlugin.log(e);
		}
	}
	return false;
}
 
Example #15
Source File: ExpandWithConstructorsConfigurationBlock.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Creates the type hierarchy for type selection.
 */
private void doBrowseTypes() {
	IRunnableContext context= new BusyIndicatorRunnableContext();
	IJavaSearchScope scope= SearchEngine.createWorkspaceScope();
	int style= IJavaElementSearchConstants.CONSIDER_ALL_TYPES;
	try {
		SelectionDialog dialog= JavaUI.createTypeDialog(getShell(), context, scope, style, false, fNameDialogField.getText());
		dialog.setTitle(CallHierarchyMessages.CallHierarchyTypesOrMembersDialog_ChooseTypeDialog_title);
		dialog.setMessage(CallHierarchyMessages.CallHierarchyTypesOrMembersDialog_ChooseTypeDialog_description);
		if (dialog.open() == Window.OK) {
			IType res= (IType)dialog.getResult()[0];
			fNameDialogField.setText(res.getFullyQualifiedName('.'));
		}
	} catch (JavaModelException e) {
		ExceptionHandler.handle(e, getShell(), CallHierarchyMessages.CallHierarchyTypesOrMembersDialog_ChooseTypeDialog_title,
				CallHierarchyMessages.CallHierarchyTypesOrMembersDialog_ChooseTypeDialog_error_message);
	}
}
 
Example #16
Source File: OverrideMethodsTestCase.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void test4() throws Exception {
	ICompilationUnit cu = fPackageP.getCompilationUnit("Test4.java");
	IType testClass = cu.createType("public class Test4 implements B, E {\n}\n", null, true, null);

	List<OverridableMethod> overridableMethods = getOverridableMethods(testClass);
	checkUnimplementedMethods(new String[] { "c(Hashtable)", "e()" }, overridableMethods);

	addAndApplyOverridableMethods(testClass, overridableMethods);

	IMethod[] methods = testClass.getMethods();
	checkMethods(new String[] { "c", "e", "equals", "clone", "toString", "finalize", "hashCode" }, methods);

	IImportDeclaration[] imports = cu.getImports();
	checkImports(new String[] { "java.util.Hashtable", "java.util.NoSuchElementException" }, imports);
}
 
Example #17
Source File: GenericRefactoringHandleTransplanter.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
protected ITypeParameter transplantHandle(IMember parent, ITypeParameter element) {
	switch (parent.getElementType()) {
		case IJavaElement.TYPE:
			return ((IType) parent).getTypeParameter(element.getElementName());
		case IJavaElement.METHOD:
			return ((IMethod) parent).getTypeParameter(element.getElementName());
		default:
			throw new IllegalStateException(element.toString());
	}
}
 
Example #18
Source File: MatchLocator.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public MatchLocator(
	SearchPattern pattern,
	SearchRequestor requestor,
	IJavaSearchScope scope,
	IProgressMonitor progressMonitor) {

	this.pattern = pattern;
	this.patternLocator = PatternLocator.patternLocator(this.pattern);
	this.matchContainer = this.patternLocator == null ? 0 : this.patternLocator.matchContainer();
	this.requestor = requestor;
	this.scope = scope;
	this.progressMonitor = progressMonitor;
	if (pattern instanceof PackageDeclarationPattern) {
		this.searchPackageDeclaration = true;
	} else if (pattern instanceof OrPattern) {
		this.searchPackageDeclaration = ((OrPattern)pattern).hasPackageDeclaration();
	} else {
		this.searchPackageDeclaration = false;
	}
	if (pattern instanceof MethodPattern) {
	    IType type = ((MethodPattern) pattern).declaringType;
	    if (type != null && !type.isBinary()) {
	    	SourceType sourceType = (SourceType) type;
	    	IMember local = sourceType.getOuterMostLocalContext();
	    	if (local instanceof IMethod) { // remember this method's range so we don't purge its statements.
	    		try {
	    			ISourceRange range = local.getSourceRange();
	    			this.sourceStartOfMethodToRetain  = range.getOffset();
	    			this.sourceEndOfMethodToRetain = this.sourceStartOfMethodToRetain + range.getLength() - 1; // offset is 0 based.
	    		} catch (JavaModelException e) {
	    			// drop silently. 
	    		}
	    	}
	    }
	}
}
 
Example #19
Source File: ExtractSupertypeProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Creates the type parameters of the new supertype.
 *
 * @param targetRewrite
 *            the target compilation unit rewrite
 * @param subType
 *            the subtype
 * @param sourceDeclaration
 *            the type declaration of the source type
 * @param targetDeclaration
 *            the type declaration of the target type
 */
protected final void createTypeParameters(final CompilationUnitRewrite targetRewrite, final IType subType, final AbstractTypeDeclaration sourceDeclaration, final AbstractTypeDeclaration targetDeclaration) {
	Assert.isNotNull(targetRewrite);
	Assert.isNotNull(sourceDeclaration);
	Assert.isNotNull(targetDeclaration);
	if (sourceDeclaration instanceof TypeDeclaration) {
		TypeParameter parameter= null;
		final ListRewrite rewrite= targetRewrite.getASTRewrite().getListRewrite(targetDeclaration, TypeDeclaration.TYPE_PARAMETERS_PROPERTY);
		for (final Iterator<TypeParameter> iterator= ((TypeDeclaration) sourceDeclaration).typeParameters().iterator(); iterator.hasNext();) {
			parameter= iterator.next();
			final ASTNode node= ASTNode.copySubtree(targetRewrite.getAST(), parameter);
			rewrite.insertLast(node, null);
		}
	}
}
 
Example #20
Source File: PreconditionExaminer.java    From JDeodorant with MIT License 5 votes vote down vote up
private boolean superclassInheritedOnlyByRefactoredSubclasses(ITypeBinding commonSuperTypeOfSourceTypeDeclarations,
		ITypeBinding typeBinding1, ITypeBinding typeBinding2) {
	if(!commonSuperTypeOfSourceTypeDeclarations.getQualifiedName().equals("java.lang.Object")) {
		CompilationUnitCache cache = CompilationUnitCache.getInstance();
		Set<IType> subTypes = cache.getSubTypes((IType)commonSuperTypeOfSourceTypeDeclarations.getJavaElement());
		IType type1 = (IType)typeBinding1.getJavaElement();
		IType type2 = (IType)typeBinding2.getJavaElement();
		if(subTypes.size() == 2 && subTypes.contains(type1) && subTypes.contains(type2) &&
				cache.getSubTypes(type1).isEmpty() && cache.getSubTypes(type2).isEmpty()) {
			return true;
		}
	}
	return false;
}
 
Example #21
Source File: RenameVirtualMethodProcessor.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
private IMethod[] relatedTypeDeclaresMethodName(IProgressMonitor pm, IMethod method, String newName) throws CoreException {
	try{
		Set<IMethod> result= new HashSet<>();
		Set<IType> types= getRelatedTypes();
		pm.beginTask("", types.size()); //$NON-NLS-1$
		for (Iterator<IType> iter= types.iterator(); iter.hasNext(); ) {
			final IMethod found= Checks.findMethod(method, iter.next());
			final IType declaring= found.getDeclaringType();
			result.addAll(Arrays.asList(hierarchyDeclaresMethodName(new SubProgressMonitor(pm, 1), declaring.newTypeHierarchy(new SubProgressMonitor(pm, 1)), found, newName)));
		}
		return result.toArray(new IMethod[result.size()]);
	} finally {
		pm.done();
	}
}
 
Example #22
Source File: RenameTypeProcessor.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
private void analyzeImportedTypes(IType[] types, RefactoringStatus result, IImportDeclaration imp) throws CoreException {
	for (int i = 0; i < types.length; i++) {
		//could this be a problem (same package imports)?
		if (JdtFlags.isPublic(types[i]) && types[i].getElementName().equals(getNewElementName())) {
			String msg = Messages.format(RefactoringCoreMessages.RenameTypeRefactoring_name_conflict1,
					new Object[] { JavaElementLabels.getElementLabel(types[i], JavaElementLabels.ALL_FULLY_QUALIFIED), BasicElementLabels.getPathLabel(getCompilationUnit(imp).getPath(), false) });
			result.addError(msg, JavaStatusContext.create(imp));
		}
	}
}
 
Example #23
Source File: SortMembersAction.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private ICompilationUnit getSelectedCompilationUnit(IStructuredSelection selection) {
	if (selection.size() == 1) {
		Object element= selection.getFirstElement();
		if (element instanceof ICompilationUnit) {
			return (ICompilationUnit) element;
		} else if (element instanceof IType) {
			IType type= (IType) element;
			if (type.getParent() instanceof ICompilationUnit) { // only top level types
				return type.getCompilationUnit();
			}
		}
	}
	return null;
}
 
Example #24
Source File: ASTNodeFinder.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public AbstractMethodDeclaration findMethod(IMethod methodHandle) {
	TypeDeclaration typeDecl = findType((IType)methodHandle.getParent());
	if (typeDecl == null) return null;
	AbstractMethodDeclaration[] methods = typeDecl.methods;
	if (methods != null) {
		char[] selector = methodHandle.getElementName().toCharArray();
		String[] parameterTypeSignatures = methodHandle.getParameterTypes();
		int parameterCount = parameterTypeSignatures.length;
		nextMethod: for (int i = 0, length = methods.length; i < length; i++) {
			AbstractMethodDeclaration method = methods[i];
			if (CharOperation.equals(selector, method.selector)) {
				Argument[] args = method.arguments;
				int argsLength = args == null ? 0 : args.length;
				if (argsLength == parameterCount) {
					for (int j = 0; j < parameterCount; j++) {
						TypeReference type = args[j].type;
						String signature = Util.typeSignature(type);
						if (!signature.equals(parameterTypeSignatures[j])) {
							continue nextMethod;
						}
					}
					return method;
				}
			}
		}
	}
	return null;
}
 
Example #25
Source File: GWTMavenRuntime.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Find the classpath for get-dev.jar which is used to run super dev mode.
 *
 * @return IClasspathEntry for the path to gwt-dev.jar
 * @throws JavaModelException
 */
private IClasspathEntry findGwtCodeServerClasspathEntry() throws JavaModelException {
  IType type = javaProject.findType(GwtLaunchConfigurationProcessorUtilities.GWT_CODE_SERVER);
  if (type == null) {
    return null;
  }

  IPackageFragmentRoot packageFragmentRoot = (IPackageFragmentRoot) type
      .getAncestor(IJavaElement.PACKAGE_FRAGMENT_ROOT);
  if (packageFragmentRoot.getKind() == IPackageFragmentRoot.K_BINARY) {
    return JavaCore.newLibraryEntry(packageFragmentRoot.getPath(), null, null);
  }

  return null;
}
 
Example #26
Source File: ParameterizedType.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
@Override
protected void initialize(ITypeBinding binding, IType javaElementType) {
	Assert.isTrue(binding.isParameterizedType());
	super.initialize(binding, javaElementType);
	TypeEnvironment environment= getEnvironment();
	fTypeDeclaration= (GenericType)environment.create(binding.getTypeDeclaration());
	ITypeBinding[] typeArguments= binding.getTypeArguments();
	fTypeArguments= new TType[typeArguments.length];
	for (int i= 0; i < typeArguments.length; i++) {
		fTypeArguments[i]= environment.create(typeArguments[i]);
	}
}
 
Example #27
Source File: PotentialProgrammingProblemsFix.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
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);
			}
		}
	}
}
 
Example #28
Source File: TemplateCustomPropertiesPage.java    From M2Doc with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Opens the class selection dialog.
 * 
 * @param tokenViewer
 *            the token {@link Viewer}
 * @param servicesTable
 *            the service {@link Viewer}
 * @param customProperties
 *            the {@link TemplateCustomProperties}
 */
private void openClassSelectionDialog(Viewer tokenViewer, Viewer servicesTable,
        final TemplateCustomProperties customProperties) {
    final IJavaSearchScope scope = SearchEngine.createWorkspaceScope();
    final FilteredTypesSelectionDialog dialog = new FilteredTypesSelectionDialog(
            Display.getCurrent().getActiveShell(), true, PlatformUI.getWorkbench().getProgressService(), scope,
            IJavaSearchConstants.CLASS);
    if (dialog.open() == Dialog.OK && dialog.getResult() != null && dialog.getResult().length != 0) {
        for (Object object : dialog.getResult()) {
            IPath parentPath = ((IType) object).getParent().getPath();
            if (parentPath.getFileExtension().equals("jar")) {
                int indexOfUnderscore = parentPath.lastSegment().indexOf('_');
                if (indexOfUnderscore > -1) {
                    final String pluginName = parentPath.lastSegment().substring(0, indexOfUnderscore);
                    customProperties.getServiceClasses().put(((IType) object).getFullyQualifiedName(), pluginName);
                } else {
                    customProperties.getServiceClasses().put(((IType) object).getFullyQualifiedName(), "");
                }
            } else {
                final String bundleName = getBundleName((IType) object);
                if (bundleName != null) {
                    customProperties.getServiceClasses().put(((IType) object).getFullyQualifiedName(), bundleName);
                } else {
                    customProperties.getServiceClasses().put(((IType) object).getFullyQualifiedName(),
                            ((IType) object).getJavaProject().getProject().getName());
                }
            }
        }
        tokenViewer.refresh();
        servicesTable.refresh();
        templateVariablesProperties.validatePage(customProperties);
    }
}
 
Example #29
Source File: ExtractClassRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private RefactoringStatus checkPackageClass() {
	RefactoringStatus status= new RefactoringStatus();
	IType type= fDescriptor.getType();
	IPackageFragmentRoot ancestor= (IPackageFragmentRoot) type.getAncestor(IJavaElement.PACKAGE_FRAGMENT_ROOT);
	IPackageFragment packageFragment= ancestor.getPackageFragment(fDescriptor.getPackage());
	if (packageFragment.getCompilationUnit(fDescriptor.getClassName() + JavaModelUtil.DEFAULT_CU_SUFFIX).exists())
		status.addError(Messages.format(RefactoringCoreMessages.ExtractClassRefactoring_error_toplevel_name_clash, new Object[] { BasicElementLabels.getJavaElementName(fDescriptor.getClassName()), BasicElementLabels.getJavaElementName(fDescriptor.getPackage()) }));
	return status;
}
 
Example #30
Source File: MethodContentGenerations.java    From jenerate with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Creates the equals method content prefix
 * 
 * @param data the data to extract configuration from
 * @param objectClass the class where the equals method is being generated
 * @return the equals method prefix
 */
public static String createEqualsContentPrefix(EqualsHashCodeGenerationData data, IType objectClass) {
    StringBuffer content = new StringBuffer();
    boolean useBlockInIfStatements = data.useBlockInIfStatements();
    if (data.compareReferences()) {
        content.append("if (this == other)");
        content.append(useBlockInIfStatements ? "{\n" : "");
        content.append(" return true;");
        content.append(useBlockInIfStatements ? "\n}\n" : "");
    }

    if (data.useClassComparison()) {
        content.append("if (other == null)");
        content.append(useBlockInIfStatements ? "{\n" : "");
        content.append(" return false;");
        content.append(useBlockInIfStatements ? "\n}\n" : "");
        content.append("if ( !getClass().equals(other.getClass()))");
        content.append(useBlockInIfStatements ? "{\n" : "");
        content.append(" return false;");
        content.append(useBlockInIfStatements ? "\n}\n" : "");
    } else if (data.useClassCast()) {
        content.append("if ( !");
        content.append(objectClass.getElementName());
        content.append(".class.isInstance(other)");
        content.append(")");
        content.append(useBlockInIfStatements ? "{\n" : "");
        content.append(" return false;");
        content.append(useBlockInIfStatements ? "\n}\n" : "");
    } else {
        content.append("if ( !(other instanceof ");
        content.append(objectClass.getElementName());
        content.append(") )");
        content.append(useBlockInIfStatements ? "{\n" : "");
        content.append(" return false;");
        content.append(useBlockInIfStatements ? "\n}\n" : "");
    }
    return content.toString();
}