public static ExecutableElement findMethod(CompilationInfo javac, TypeElement clazz, String name, List<? extends VariableElement> params, boolean includeSupertypes) { if (name == null || name.length() == 0) { return null; } TypeElement c = clazz; while (true) { for (Element elm : c.getEnclosedElements()) { if (ElementKind.METHOD == elm.getKind()) { ExecutableElement m = (ExecutableElement) elm; if (name.contentEquals(m.getSimpleName()) && compareParams(javac, params, m.getParameters()) && isAccessible(javac, clazz, m)) { return m; } } } TypeMirror superType = c.getSuperclass(); if (!includeSupertypes || superType.getKind() == TypeKind.NONE) { return null; } c = (TypeElement) ((DeclaredType) superType).asElement(); } }
public void validate(CompilationInfo info) { TypeElement test = info.getElements().getTypeElement("test.Test"); VariableElement var = ElementFilter.fieldsIn(test.getEnclosedElements()).get(0); List<? extends ExecutableElement> methods = ElementFilter.methodsIn(test.getEnclosedElements()); assertEquals(1, methods.size()); ExecutableElement method = methods.get(0); TypeMirror type = info.getTypes().asMemberOf((DeclaredType)test.asType(), var); if (getter) { assertTrue(info.getTypes().isSameType(type, method.getReturnType())); assertEquals(type.getKind() == TypeKind.BOOLEAN ? "isTest" : "getTest", method.getSimpleName().toString()); assertEquals(0, method.getParameters().size()); } else { assertTrue(info.getTypes().isSameType(info.getTypes().getNoType(TypeKind.VOID), method.getReturnType())); assertEquals("setTest", method.getSimpleName().toString()); assertEquals(1, method.getParameters().size()); assertTrue(info.getTypes().isSameType(type, method.getParameters().get(0).asType())); } }
@Override public Void visitClass(ClassTree node, Void p) { TypeElement te = (TypeElement) trees.getElement(getCurrentPath()); Set<PhaseDescription> expected = new HashSet<>(); for (AnnotationMirror am : getTriggersCompleteAnnotation(te)) { TypeMirror of = (TypeMirror) findAttribute(am, "of").getValue(); Name ofName = elements.getBinaryName((TypeElement) ((DeclaredType) of).asElement()); Element at = (Element) findAttribute(am, "at").getValue(); Phase phase = Phase.valueOf(at.getSimpleName().toString()); expected.add(new PhaseDescription(ofName.toString(), phase)); } if (!expected.isEmpty()) topLevel2Expected.put(elements.getBinaryName(te).toString(), expected); return super.visitClass(node, p); }
/** * Unbox a wrapper type into a TypeKind. Some additional types are mapped to TypeKinds which cannot really appear in * expressions (at least I hope) * * @param tm * @return */ private static TypeKind unboxBoxed(TypeMirror tm) { TypeElement te = (TypeElement)((DeclaredType)tm).asElement(); String qn = te.getQualifiedName().toString(); if (!qn.startsWith("java.lang.")) { // NO18N if (qn.equals("java.math.BigInteger")) { // NOI18N return TypeKind.WILDCARD; } return null; } switch (qn.substring(10)) { case "Short": return TypeKind.SHORT; // NOI18N case "Long": return TypeKind.LONG; // NOI18N case "Byte": return TypeKind.BYTE; // NOI18N case "Integer": return TypeKind.INT; // NOI18N case "Double": return TypeKind.DOUBLE; // NOI18N case "Float": return TypeKind.FLOAT; // NOI18N case "Character": return TypeKind.CHAR; // NOI18N case "String": return TypeKind.OTHER; // NOI18N case "Object": return TypeKind.PACKAGE; // NOI18N } return null; }
/** * Convert typemirror of an anonymous class to supertype/iface * * @return typemirror of supertype/iface, initial tm if not anonymous */ public static TypeMirror convertIfAnonymous(TypeMirror tm) { //anonymous class? Set<ElementKind> fm = EnumSet.of(ElementKind.METHOD, ElementKind.FIELD); if (tm instanceof DeclaredType) { Element el = ((DeclaredType) tm).asElement(); //XXX: the null check is needed for lambda type, not covered by test: if (el != null && (el.getSimpleName().length() == 0 || fm.contains(el.getEnclosingElement().getKind()))) { List<? extends TypeMirror> interfaces = ((TypeElement) el).getInterfaces(); if (interfaces.isEmpty()) { tm = ((TypeElement) el).getSuperclass(); } else { tm = interfaces.get(0); } } } return tm; }
private String findViewTypeOfPresenter(TypeElement presenterElement) { TypeElement currentClass = presenterElement; while (currentClass != null) { if (currentClass.getSuperclass() instanceof DeclaredType) { List<? extends TypeMirror> superClassParameters = ((DeclaredType) currentClass.getSuperclass()).getTypeArguments(); if (superClassParameters.size() == 1) { String type = superClassParameters.get(0).toString(); if (!"V".equals(type)) return type; } } currentClass = getSuperClass(currentClass); } return ""; }
@Override public StringBuilder visitDeclared(DeclaredType t, Boolean p) { Element e = t.asElement(); if (e instanceof TypeElement) { TypeElement te = (TypeElement)e; DEFAULT_VALUE.append((p ? te.getQualifiedName() : te.getSimpleName()).toString()); Iterator<? extends TypeMirror> it = t.getTypeArguments().iterator(); if (it.hasNext()) { DEFAULT_VALUE.append("<"); //NOI18N while(it.hasNext()) { visit(it.next(), p); if (it.hasNext()) DEFAULT_VALUE.append(", "); //NOI18N } DEFAULT_VALUE.append(">"); //NOI18N } return DEFAULT_VALUE; } else { return DEFAULT_VALUE.append(UNKNOWN); //NOI18N } }
@Override public Completer createCompleter(CompletionContext ctx) { FxProperty p = ctx.getEnclosingProperty(); if (p == null || p.getType() == null) { return null; } TypeMirror m = p.getType().resolve(ctx.getCompilationInfo()); if (m.getKind() == TypeKind.BOOLEAN) { return new EnumValueCompleter(ctx); } if (m.getKind() != TypeKind.DECLARED) { return null; } DeclaredType t = (DeclaredType)m; TypeElement tel = (TypeElement)t.asElement(); if (tel.getQualifiedName().contentEquals("java.lang.Boolean")) { return new EnumValueCompleter(ctx); } if (tel.getKind() == ElementKind.ENUM) { return new EnumValueCompleter(ctx, tel); } else { return null; } }
TypeHierarchyCollector createTypeHierarchyCollector(final Reporter reporter, final Element element) { return new TypeHierarchyCollector() { @Override protected String stringify(DeclaredType input, TypevarContext context) { TypeStringProvider provider = new TypeStringProvider( reporter, element, input, newTypeStringResolver(), context.parameters.toArray(new String[0]), context.arguments.toArray(new String[0])); provider.collectUnresolvedYetArgumentsTo(this.unresolvedYetArguments); provider.process(); return provider.returnTypeName(); } }; }
static TypeMirror resolveReturnType( ProcessingEnvironment processing, ExecutableElement method, TypeElement typeElement) { method = CachingElements.getDelegate(method); TypeMirror returnType = method.getReturnType(); // We do not support parametrized accessor methods, // but we do support inheriting parametrized accessors, which // we supposedly parametrized with actual type parameters as // our target class could not define formal type parameters also. if (returnType.getKind() == TypeKind.TYPEVAR) { return asInheritedMemberReturnType(processing, typeElement, method); } else if (returnType.getKind() == TypeKind.DECLARED || returnType.getKind() == TypeKind.ERROR) { if (!((DeclaredType) returnType).getTypeArguments().isEmpty()) { return asInheritedMemberReturnType(processing, typeElement, method); } } return returnType; }
@Value.Lazy List<TypeElement> includedTypes() { Optional<IncludeMirror> includes = include(); ImmutableList<TypeMirror> typeMirrors = includes.isPresent() ? ImmutableList.copyOf(includes.get().valueMirror()) : ImmutableList.<TypeMirror>of(); FluentIterable<TypeElement> typeElements = FluentIterable.from(typeMirrors) .filter(DeclaredType.class) .transform(DeclatedTypeToElement.FUNCTION); ImmutableSet<String> uniqueTypeNames = typeElements .filter(IsPublic.PREDICATE) .transform(ElementToName.FUNCTION) .toSet(); if (uniqueTypeNames.size() != typeMirrors.size()) { report().annotationNamed(IncludeMirror.simpleName()) .warning("Some types were ignored, non-supported for inclusion: duplicates," + " non declared reference types, non-public"); } return typeElements.toList(); }
private MethodSpec makeOverrideMethod(ExecutableElement method) { TypeName requestTypeName = getRequestClassName(method); DeclaredType responseReturnType = (DeclaredType) method.getReturnType(); TypeMirror responseBean = responseReturnType.getTypeArguments().get(0); MethodSpec.Builder request = MethodSpec.methodBuilder(method.getSimpleName().toString()) .returns(ParameterizedTypeName.get(ClassName.get(Response.class), ClassName.get(responseBean))) .addModifiers(Modifier.PUBLIC) .addAnnotation(Override.class); String initializeStatement = "return new " + processorElement.simpleName() + "_" + method.getSimpleName(); if (!method.getParameters().isEmpty()) { request.addParameter(requestTypeName, "request"); request.addStatement(initializeStatement + "(request)"); } else request.addStatement(initializeStatement + "($T.VOID_REQUEST)", RequestBean.class); return request.build(); }
private void appendTypeArguments(TypeMirror type, DeclaredType declaredType) { List<? extends TypeMirror> arguments = declaredType.getTypeArguments(); if (!arguments.isEmpty()) { buffer.append('<'); boolean notFirst = false; for (TypeMirror argument : arguments) { typeAnnotationHandle(argument); if (notFirst) { buffer.append(',').append(' '); } notFirst = true; int mark = buffer.length(); caseType(argument); cutTypeArgument(type, mark); } buffer.append('>'); } }
@Override public TypeMirror visitDeclared(DeclaredType t, CompilationInfo p) { if (t.getTypeArguments().isEmpty()) { return t; } List<TypeMirror> newArgs = new ArrayList<TypeMirror>(t.getTypeArguments().size()); for (TypeMirror tm : t.getTypeArguments()) { newArgs.add(visit(tm, p)); } TypeMirror enclosing = t.getEnclosingType(); if (enclosing != null) { enclosing = visit(enclosing, p); } return p.getTypes().getDeclaredType( (DeclaredType)enclosing, (TypeElement)t.asElement(), newArgs.toArray(new TypeMirror[newArgs.size()])); }
private void replaceWithSuperType(TreePath path, VariableTree oldVarTree, VariableElement varElement, Element superTypeElement) { Types types = workingCopy.getTypes(); TypeMirror supTypeErasure = types.erasure(superTypeElement.asType()); DeclaredType varType = (DeclaredType) varElement.asType(); TypeMirror theType = null; List<TypeMirror> supertypes = new LinkedList(types.directSupertypes(varType)); while(!supertypes.isEmpty()) { TypeMirror supertype = supertypes.remove(0); if(types.isSameType(types.erasure(supertype), supTypeErasure)) { theType = supertype; break; } supertypes.addAll(types.directSupertypes(supertype)); } if(theType == null) { theType = supTypeErasure; } Tree superTypeTree = make.Type(theType); ExpressionTree oldInitTree = oldVarTree.getInitializer(); ModifiersTree oldModifiers = oldVarTree.getModifiers(); Tree newTree = make.Variable(oldModifiers, oldVarTree.getName(), superTypeTree, oldInitTree); rewrite(oldVarTree, newTree); }
private Map<String, Set<? extends Element>> processElements(Set<? extends Element> annotatedElements) { final Map<String, Set<? extends Element>> mapGeneratedFileNameToOrginatingElements = new HashMap<>(); for (Element annotatedElement : annotatedElements) { String nameOfClassContainingElement = getEnclosingClassName(annotatedElement); TypeMirror superclass = ((TypeElement) annotatedElement).getSuperclass(); if (superclass != null) { Element superClassAsElement = ((DeclaredType) superclass).asElement(); if (superClassAsElement.getAnnotation(Annotation1.class) != null) { String nameOfSuperClassContainingElement = getEnclosingClassName(superClassAsElement); final String finalClassName = getClass().getSimpleName() // + "_" // + nameOfClassContainingElement // + "_" // + nameOfSuperClassContainingElement // + "Gen0"; mapGeneratedFileNameToOrginatingElements.put(finalClassName, new HashSet<>(asList(annotatedElement, superClassAsElement))); } } } return mapGeneratedFileNameToOrginatingElements; }
/** * Returns the non-object superclass of the type with the proper type parameters. * An absent Optional is returned if there is no non-Object superclass. */ public static Optional<DeclaredType> nonObjectSuperclass(final Types types, Elements elements, DeclaredType type) { checkNotNull(types); checkNotNull(elements); checkNotNull(type); final TypeMirror objectType = elements.getTypeElement(Object.class.getCanonicalName()).asType(); // It's guaranteed there's only a single CLASS superclass because java doesn't have multiple // class inheritance. TypeMirror superclass = getOnlyElement(FluentIterable.from(types.directSupertypes(type)) .filter(new Predicate<TypeMirror>() { @Override public boolean apply(TypeMirror input) { return input.getKind().equals(TypeKind.DECLARED) && (MoreElements.asType( MoreTypes.asDeclared(input).asElement())).getKind().equals(ElementKind.CLASS) && !types.isSameType(objectType, input); } }), null); return superclass != null ? Optional.of(MoreTypes.asDeclared(superclass)) : Optional.<DeclaredType>absent(); }
private Predicate<Element> createAccessibilityFilter(AnalyzeTask at, TreePath tp) { Scope scope = at.trees().getScope(tp); return el -> { switch (el.getKind()) { case ANNOTATION_TYPE: case CLASS: case ENUM: case INTERFACE: return at.trees().isAccessible(scope, (TypeElement) el); case PACKAGE: case EXCEPTION_PARAMETER: case PARAMETER: case LOCAL_VARIABLE: case RESOURCE_VARIABLE: return true; default: TypeMirror type = el.getEnclosingElement().asType(); if (type.getKind() == TypeKind.DECLARED) return at.trees().isAccessible(scope, el, (DeclaredType) type); else return true; } }; }
public static TypeMirror stripCollection(TypeMirror passedType, Types types) { if (TypeKind.DECLARED != passedType.getKind() || !(passedType instanceof DeclaredType)) { return passedType; } TypeElement passedTypeElement = (TypeElement) types.asElement(passedType); String passedTypeQualifiedName = passedTypeElement.getQualifiedName().toString(); //does not include type parameter info Class passedTypeClass = null; try { passedTypeClass = Class.forName(passedTypeQualifiedName); } catch (ClassNotFoundException e) { //just let passedTypeClass be null } if (passedTypeClass != null && Collection.class.isAssignableFrom(passedTypeClass)) { List<? extends TypeMirror> passedTypeArgs = ((DeclaredType)passedType).getTypeArguments(); if (passedTypeArgs.isEmpty()) { return passedType; } return passedTypeArgs.get(0); } return passedType; }
@Override public Boolean visitNewClass(NewClassTree node, Void p) { TypeMirror tm = ci.getTrees().getTypeMirror(getCurrentPath()); if (tm == null || tm.getKind() != TypeKind.DECLARED) { return false; } TypeElement el = (TypeElement)((DeclaredType)tm).asElement(); if (el == null) { return false; } Name n = el.getQualifiedName(); boolean res = n.contentEquals("java.lang.StringBuilder") || n.contentEquals("java.lang.StringBuffer"); // NOI18N // check if there is some initial contents if (node.getArguments().size() == 1 && Utilities.isJavaString(ci, ci.getTrees().getTypeMirror(new TreePath(getCurrentPath(), node.getArguments().get(0))))) { hasContents = true; } return res; }
static TypeElement getFirstTypeArgument(TypeMirror type) { if (TypeKind.DECLARED != type.getKind()) { return null; } List<? extends TypeMirror> typeArgs = ((DeclaredType)type).getTypeArguments(); if (typeArgs.size() != 1) { return null; } TypeMirror typeArg = typeArgs.iterator().next(); if (TypeKind.DECLARED != typeArg.getKind()) { return null; } Element typeArgElement = ((DeclaredType)typeArg).asElement(); if (ElementKind.CLASS != typeArgElement.getKind()) { return null; } return (TypeElement)typeArgElement; }
@Override public StringBuilder visitWildcard(WildcardType t, Boolean p) { int len = DEFAULT_VALUE.length(); DEFAULT_VALUE.append("?"); //NOI18N TypeMirror bound = t.getSuperBound(); if (bound == null) { bound = t.getExtendsBound(); if (bound != null) { DEFAULT_VALUE.append(" extends "); //NOI18N if (bound.getKind() == TypeKind.WILDCARD) { bound = ((WildcardType)bound).getSuperBound(); } visit(bound, p); } else if (len == 0) { bound = SourceUtils.getBound(t); if (bound != null && (bound.getKind() != TypeKind.DECLARED || !((TypeElement)((DeclaredType)bound).asElement()).getQualifiedName().contentEquals("java.lang.Object"))) { //NOI18N DEFAULT_VALUE.append(" extends "); //NOI18N visit(bound, p); } } } else { DEFAULT_VALUE.append(" super "); //NOI18N visit(bound, p); } return DEFAULT_VALUE; }
private void appendAnnotation(StringBuilder sb, AnnotationMirror annotationDesc, boolean topLevel) { DeclaredType annotationType = annotationDesc.getAnnotationType(); if (annotationType != null && (!topLevel || isDocumented(annotationType))) { appendType(sb, annotationType, false, false, true); Map<? extends ExecutableElement, ? extends AnnotationValue> values = annotationDesc.getElementValues(); if (!values.isEmpty()) { sb.append('('); //NOI18N for (Iterator<? extends Map.Entry<? extends ExecutableElement, ? extends AnnotationValue>> it = values.entrySet().iterator(); it.hasNext();) { Map.Entry<? extends ExecutableElement, ? extends AnnotationValue> value = it.next(); createLink(sb, value.getKey(), value.getKey().getSimpleName()); sb.append('='); //NOI18N appendAnnotationValue(sb, value.getValue()); if (it.hasNext()) sb.append(","); //NOI18N } sb.append(')'); //NOI18N } if (topLevel) sb.append("<br>"); //NOI18N } }
/** * uses FQNs where possible since javadoc does not match imports for * parameter types */ private CharSequence resolveTypeName(TypeMirror asType, boolean isVarArgs) { CharSequence ptype; if (asType.getKind() == TypeKind.DECLARED) { // snip generics Element e = ((DeclaredType) asType).asElement(); ptype = e.getKind().isClass() || e.getKind().isInterface() ? ((TypeElement) e).getQualifiedName() : e.getSimpleName(); } else if (asType.getKind() == TypeKind.TYPEVAR) { do { // Type Erasure JLS 4.6 asType = ((TypeVariable) asType).getUpperBound(); } while (asType.getKind() == TypeKind.TYPEVAR); ptype = resolveTypeName(asType, isVarArgs); } else if (isVarArgs && asType.getKind() == TypeKind.ARRAY) { ptype = resolveTypeName(((ArrayType)asType).getComponentType(), false) + "..."; //NOI18N } else { ptype = asType.toString(); } return ptype; }
private MethodTree createGetter(ModifiersTree mods, TypeMirror valueType) { StringBuilder getterName = GeneratorUtils.getCapitalizedName(config.getName()); getterName.insert(0, valueType.getKind() == TypeKind.BOOLEAN ? "is" : "get"); ReturnTree returnTree = make.Return(make.MethodInvocation(Collections.EMPTY_LIST, make.MemberSelect(make.Identifier(config.getName()), hasGet ? "get" : "getValue"), Collections.EMPTY_LIST)); BlockTree getterBody = make.Block(Collections.singletonList(returnTree), false); Tree valueTree; if (valueType.getKind() == TypeKind.DECLARED) { valueTree = make.QualIdent(((DeclaredType) valueType).asElement()); } else if (valueType.getKind().isPrimitive()) { valueTree = make.PrimitiveType(valueType.getKind()); } else { valueTree = make.Identifier(valueType.toString()); } MethodTree getter = make.Method(mods, getterName, valueTree, Collections.EMPTY_LIST, Collections.EMPTY_LIST, Collections.EMPTY_LIST, getterBody, null); return getter; }
static boolean hasUncheckedWarning(TypeMirror type) { switch (type.getKind()) { case DECLARED: DeclaredType declared = (DeclaredType) type; for (TypeMirror typeParam : declared.getTypeArguments()) { if (hasUncheckedWarning(typeParam)) { return true; } } return false; case TYPEVAR: return true; case WILDCARD: return ((WildcardType) type).getExtendsBound() != null; case ARRAY: return hasUncheckedWarning(((ArrayType) type).getComponentType()); default: return false; } }
@Override public void run(CompilationController controller) throws Exception { controller.toPhase(JavaSource.Phase.ELEMENTS_RESOLVED); if (implClass == null) { return; } TypeElement te = JavaUtils.findClassElementByBinaryName(implClass, controller); if (te == null) { return; } FactoryMethodFinder factoryMethodFinder = new FactoryMethodFinder( te, factoryMethodName, staticFlag, controller.getElementUtilities()); List<ExecutableElement> methods = factoryMethodFinder.findMethods(); if (methods.size() != 1) { return; } ExecutableElement method = methods.get(0); if (method.getReturnType().getKind() != TypeKind.DECLARED) { return; } wasClassResolved.set(true); DeclaredType dt = (DeclaredType) method.getReturnType(); resolvedClass[0] = ElementUtilities.getBinaryName((TypeElement) dt.asElement()); }
private void addListProperty(ExecutableElement m, String propName) { FxProperty pi = new FxProperty(propName, FxDefinitionKind.LIST); pi.setSimple(false); pi.setAccessor(ElementHandle.create(m)); // must extract type arguments; assume there's a DeclaredType DeclaredType t = ((DeclaredType)m.getReturnType()); ExecutableType getterType = findListGetMethod(t); pi.setType(TypeMirrorHandle.create(getterType.getReturnType())); pi.setObservableAccessors(pi.getAccessor()); registerProperty(pi); }
public boolean isAccessible(Scope scope, Element member, DeclaredType type) { if (scope instanceof JavacScope && member instanceof Symbol && type instanceof com.sun.tools.javac.code.Type) { Env<AttrContext> env = ((JavacScope) scope).env; return resolve.isAccessible(env, (com.sun.tools.javac.code.Type)type, (Symbol)member, true); } else return false; }
/** * Finds the declaration of the enclosing's type parameter. * * @param values * @param enclosing a TypeElement whose type arguments we desire * @param target the TypeMirror of the type as described by the enclosing * @return */ public TypeMirror getDeclaredType(Collection<TypeMirror> values, TypeElement enclosing, TypeMirror target) { TypeElement targetElement = asTypeElement(target); List<? extends TypeParameterElement> targetTypeArgs = targetElement.getTypeParameters(); if (targetTypeArgs.isEmpty()) { return target; } List<? extends TypeParameterElement> enclosingTypeArgs = enclosing.getTypeParameters(); List<TypeMirror> targetTypeArgTypes = new ArrayList<>(targetTypeArgs.size()); if (enclosingTypeArgs.isEmpty()) { for (TypeMirror te : values) { List<? extends TypeMirror> typeArguments = ((DeclaredType)te).getTypeArguments(); if (typeArguments.size() >= targetTypeArgs.size()) { for (int i = 0 ; i < targetTypeArgs.size(); i++) { targetTypeArgTypes.add(typeArguments.get(i)); } break; } } // we found no matches in the hierarchy if (targetTypeArgTypes.isEmpty()) { return target; } } else { if (targetTypeArgs.size() > enclosingTypeArgs.size()) { return target; } for (int i = 0; i < targetTypeArgs.size(); i++) { TypeParameterElement tpe = enclosingTypeArgs.get(i); targetTypeArgTypes.add(tpe.asType()); } } TypeMirror dt = typeUtils.getDeclaredType(targetElement, targetTypeArgTypes.toArray(new TypeMirror[targetTypeArgTypes.size()])); return dt; }
private MethodTree createHashCodeMethod(WorkingCopy wc, DeclaredType type) { TreeMaker make = wc.getTreeMaker(); Set<Modifier> mods = EnumSet.of(Modifier.PUBLIC); Integer number = refactoring.getContext().lookup(Integer.class); // Used in test code int startNumber; int multiplyNumber; if (number != null) { startNumber = number.intValue(); multiplyNumber = number.intValue(); } else { startNumber = generatePrimeNumber(2, 10); multiplyNumber = generatePrimeNumber(10, 100); } List<StatementTree> statements = new ArrayList<>(); //int hash = <startNumber>; statements.add(make.Variable(make.Modifiers(EnumSet.noneOf(Modifier.class)), "hash", make.PrimitiveType(TypeKind.INT), make.Literal(startNumber))); //NOI18N TypeMirror tm = type; ExpressionTree variableRead = prepareExpression(wc, HASH_CODE_PATTERNS, tm, "delegate"); //NOI18N statements.add(make.ExpressionStatement(make.Assignment(make.Identifier("hash"), make.Binary(Tree.Kind.PLUS, make.Binary(Tree.Kind.MULTIPLY, make.Literal(multiplyNumber), make.Identifier("hash")), variableRead)))); //NOI18N statements.add(make.Return(make.Identifier("hash"))); //NOI18N BlockTree body = make.Block(statements, false); ModifiersTree modifiers = prepareModifiers(wc, mods, make, true); return make.Method(modifiers, "hashCode", make.PrimitiveType(TypeKind.INT), Collections.<TypeParameterTree>emptyList(), Collections.<VariableTree>emptyList(), Collections.<ExpressionTree>emptyList(), body, null); //NOI18N }
public static String getFullClassName(TypeMirror typeMirror) { if (!(typeMirror instanceof DeclaredType)) { return ""; } TypeElement typeElement = (TypeElement) ((DeclaredType) typeMirror).asElement(); return getFullClassName(typeElement); }
public static CompletionItem createTypeItem(CompilationInfo info, TypeElement elem, int startOffset, ReferencesCount referencesCount, boolean isDeprecated) { CompletionItem delegate = JavaCompletionItem.createTypeItem( info, elem, (DeclaredType) elem.asType(), startOffset, referencesCount, isDeprecated, false, false, false, false, false, null); return new JavadocTypeItem(delegate, startOffset); }
public TypeMirror getTypeArgument(TypeMirror typeMirror, int i) { if (typeMirror != null && typeMirror.getKind().equals(TypeKind.DECLARED)) { DeclaredType declaredType = (DeclaredType) typeMirror; TypeMirror[] args = declaredType.getTypeArguments().toArray(new TypeMirror[declaredType.getTypeArguments().size()]); return args[i]; } else throw new IllegalArgumentException(); }
private void collectHierarchyMirrors(TypeMirror typeMirror, String stringRepresentation) { if (typeMirror.getKind() != TypeKind.DECLARED || typeMirror.toString().equals(Object.class.getName())) { return; } DeclaredType declaredType = toDeclaredType(typeMirror); TypeElement e = toTypeElement(declaredType); TypevarContext context = new TypevarContext(e, stringRepresentation); collectInterfacesMirrors(declaredType, context); TypeMirror superclassMirror = e.getSuperclass(); if (superclassMirror.getKind() != TypeKind.NONE) { DeclaredType superclass = toDeclaredType(superclassMirror); String stringified = stringify(superclass, context); if (!stringified.equals(Object.class.getName())) { extendedClasses.add(toTypeElement(superclass)); extendedClassNames.add(stringified); collectHierarchyMirrors(superclass, stringified); } } for (TypeMirror m : e.getInterfaces()) { collectUnresolvedInterface(m, context); collectInterfacesMirrors(m, context); } }
private VariableTree createField(DeclaredType selectedType, ExpressionTree implementationType) { String initializer = config.getInitializer(); NewClassTree newClass = make.NewClass(null, Collections.EMPTY_LIST, implementationType, Collections.singletonList(make.Identifier(initializer)), null); VariableTree property = make.Variable( make.Modifiers(EnumSet.of(Modifier.PRIVATE, Modifier.FINAL)), config.getName(), getTypeTree(selectedType), newClass); return property; }
private boolean shouldApplyErasure(TypeMirror argument) { if (argument.getKind() == TypeKind.DECLARED) { if (((DeclaredType) argument).asElement().getModifiers().contains(Modifier.PRIVATE)) { return true; } } else { return true; } return false; }
private Iterable<Pair<ExecutableElement, ExecutableType>> newClassCandidates(AnalyzeTask at, TreePath newClassPath) { NewClassTree nct = (NewClassTree) newClassPath.getLeaf(); Element type = at.trees().getElement(new TreePath(newClassPath.getParentPath(), nct.getIdentifier())); TypeMirror targetType = at.trees().getTypeMirror(newClassPath); if (targetType == null || targetType.getKind() != TypeKind.DECLARED) { Iterable<TypeMirror> targetTypes = findTargetType(at, newClassPath); if (targetTypes == null) targetTypes = Collections.emptyList(); targetType = StreamSupport.stream(targetTypes.spliterator(), false) .filter(t -> at.getTypes().asElement(t) == type) .findAny() .orElse(at.getTypes().erasure(type.asType())); } List<Pair<ExecutableElement, ExecutableType>> candidateConstructors = new ArrayList<>(); Predicate<Element> accessibility = createAccessibilityFilter(at, newClassPath); if (targetType != null && targetType.getKind() == TypeKind.DECLARED && type != null && (type.getKind().isClass() || type.getKind().isInterface())) { for (ExecutableElement constr : ElementFilter.constructorsIn(type.getEnclosedElements())) { if (accessibility.test(constr)) { ExecutableType constrType = (ExecutableType) at.getTypes().asMemberOf((DeclaredType) targetType, constr); candidateConstructors.add(Pair.of(constr, constrType)); } } } return candidateConstructors; }
Void printExecutable(ExecutableElement e, DeclaredType dt, Boolean highlightName) { switch (e.getKind()) { case CONSTRUCTOR: modifier(e.getModifiers()); dumpTypeArguments(e.getTypeParameters()); result.append(' '); boldStartCheck(highlightName); result.append(e.getEnclosingElement().getSimpleName()); boldStopCheck(highlightName); TypeMirror memberType = null; if (dt != null) { dumpRealTypeArguments(dt.getTypeArguments()); try { memberType = info.getTypes().asMemberOf(dt, e); } catch (IllegalStateException ise) {} } if (memberType instanceof ExecutableType) { dumpArguments(e.getParameters(), ((ExecutableType) memberType).getParameterTypes()); } else { dumpArguments(e.getParameters(), null); } dumpThrows(e.getThrownTypes()); break; case METHOD: modifier(e.getModifiers()); dumpTypeArguments(e.getTypeParameters()); result.append(getTypeName(info, e.getReturnType(), true)); result.append(' '); boldStartCheck(highlightName); result.append(e.getSimpleName()); boldStopCheck(highlightName); dumpArguments(e.getParameters(), null); dumpThrows(e.getThrownTypes()); break; case INSTANCE_INIT: case STATIC_INIT: //these two cannot be referenced anyway... } return null; }