Java Code Examples for javax.lang.model.type.TypeKind

The following examples show how to use javax.lang.model.type.TypeKind. These examples are extracted from open source projects. 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 want to check out the right sidebar which shows the related API usage.
Example 1
Source Project: immutables   Source File: AccessorAttributesCollector.java    License: Apache License 2.0 6 votes vote down vote up
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;
}
 
Example 2
private void locateNestedTypes(Type type, TypeAnnotationPosition p) {
    // The number of "steps" to get from the full type to the
    // left-most outer type.
    ListBuffer<TypePathEntry> depth = new ListBuffer<>();

    Type encl = type.getEnclosingType();
    while (encl != null &&
            encl.getKind() != TypeKind.NONE &&
            encl.getKind() != TypeKind.ERROR) {
        depth = depth.append(TypePathEntry.INNER_TYPE);
        encl = encl.getEnclosingType();
    }
    if (depth.nonEmpty()) {
        p.location = p.location.prependList(depth.toList());
    }
}
 
Example 3
Source Project: RetroFacebook   Source File: RetroFacebookProcessor.java    License: Apache License 2.0 6 votes vote down vote up
private ImmutableSet<ExecutableElement> methodsToImplement(List<ExecutableElement> methods) {
  ImmutableSet.Builder<ExecutableElement> toImplement = ImmutableSet.builder();
  boolean errors = false;
  for (ExecutableElement method : methods) {
    if (method.getModifiers().contains(Modifier.ABSTRACT)
        && objectMethodToOverride(method) == ObjectMethodToOverride.NONE) {
      if (method.getParameters().isEmpty() && method.getReturnType().getKind() != TypeKind.VOID) {
        if (isReferenceArrayType(method.getReturnType())) {
          errorReporter.reportError("An @RetroFacebook class cannot define an array-valued property"
              + " unless it is a primitive array", method);
          errors = true;
        }
        toImplement.add(method);
      } else {
        toImplement.add(method);
      }
    }
  }
  if (errors) {
    throw new AbortProcessingException();
  }
  return toImplement.build();
}
 
Example 4
private void parseOnKStringUpdate(Element element, Map<TypeElement, BindingClass> targetClassMap,
                                  Set<String> erasedTargetNames) {
    TypeElement enclosingElement = (TypeElement) element.getEnclosingElement();
    BindingClass bindingClass = getOrCreateTargetClass(targetClassMap, enclosingElement, false, false);
    TypeMirror mirror = element.asType();
    if (!(mirror.getKind() == TypeKind.EXECUTABLE))
        return;
    String method = element.toString().trim();
    String methodName = method.substring(0, method.indexOf("("));
    Matcher m = Pattern.compile("\\(([^)]+)\\)").matcher(method);
    if (m.find()) {
        String[] methodTypes = m.group(1).split(",");
        UpdateKStringBinding binding = new UpdateKStringBinding(methodName, methodTypes);
        String kstring = element.getAnnotation(OnKStringChanged.class).value();
        bindingClass.addKStringUpdateBinding(kstring, binding);
    }
    erasedTargetNames.add(enclosingElement.toString());
}
 
Example 5
Source Project: android-state   Source File: StateProcessor.java    License: Eclipse Public License 1.0 6 votes vote down vote up
private CompatibilityType getCompatibilityType(Element field) {
    TypeMirror typeMirror = field.asType();
    for (CompatibilityType compatibilityType : CompatibilityType.values()) {
        if (compatibilityType == CompatibilityType.PARCELABLE_ARRAY) {
            TypeMirror arrayType = getArrayType(field);
            if (arrayType != null && isAssignable(arrayType, PARCELABLE_CLASS_NAME)) {
                return CompatibilityType.PARCELABLE_ARRAY;
            }

        } else if (compatibilityType.mGenericClass == null) {
            if (isAssignable(typeMirror, compatibilityType.mClass)) {
                return compatibilityType;
            }

        } else if (typeMirror.getKind() != TypeKind.WILDCARD) {
            if (isAssignable(mTypeUtils.erasure(typeMirror), compatibilityType.mClass)) {
                List<? extends TypeMirror> typeArguments = ((DeclaredType) typeMirror).getTypeArguments();
                if (typeArguments != null && typeArguments.size() >= 1 && isAssignable(typeArguments.get(0), compatibilityType.mGenericClass)) {
                    return compatibilityType;
                }
            }
        }
    }
    return null;
}
 
Example 6
Source Project: netbeans   Source File: GeneratorUtils.java    License: Apache License 2.0 6 votes vote down vote up
private static List<TypeElement> getAllClasses(TypeElement of) {
    List<TypeElement> result = new ArrayList<>();
    TypeMirror sup = of.getSuperclass();
    TypeElement te = sup.getKind() == TypeKind.DECLARED ? (TypeElement) ((DeclaredType)sup).asElement() : null;
    
    result.add(of);
    
    if (te != null) {
        result.addAll(getAllClasses(te));
    } else {
        if (ERR.isLoggable(ErrorManager.INFORMATIONAL)) {
            ERR.log(ErrorManager.INFORMATIONAL, "te=null, t=" + of);
        }
    }
    
    return result;
}
 
Example 7
Source Project: doma   Source File: ArrayCreateQueryMetaFactory.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected void doParameters(ArrayCreateQueryMeta queryMeta) {
  List<? extends VariableElement> parameters = methodElement.getParameters();
  int size = parameters.size();
  if (size != 1) {
    throw new AptException(Message.DOMA4002, methodElement, new Object[] {});
  }
  QueryParameterMeta parameterMeta = createParameterMeta(parameters.get(0));
  if (parameterMeta.getType().getKind() != TypeKind.ARRAY) {
    throw new AptException(Message.DOMA4076, parameterMeta.getElement(), new Object[] {});
  }
  queryMeta.setElementsParameterName(parameterMeta.getName());
  queryMeta.addParameterMeta(parameterMeta);
  if (parameterMeta.isBindable()) {
    queryMeta.addBindableParameterCtType(parameterMeta.getName(), parameterMeta.getCtType());
  }
}
 
Example 8
Source Project: openjdk-8   Source File: TestTypeKind.java    License: GNU General Public License v2.0 6 votes vote down vote up
static int testIsPrimitive() {
    int failures = 0;
    // The eight primitive types
    Set<TypeKind> primitives = EnumSet.of(BOOLEAN,  // 1
                                          BYTE,     // 2
                                          CHAR,     // 3
                                          DOUBLE,   // 4
                                          FLOAT,    // 5
                                          INT,      // 6
                                          LONG,     // 7
                                          SHORT);   // 8

    for(TypeKind tk : TypeKind.values()) {
        boolean primitiveness;
        if ((primitiveness=tk.isPrimitive()) != primitives.contains(tk) ) {
            failures++;
            System.err.println("Unexpected isPrimitive value " + primitiveness +
                               "for " + tk);
        }
    }
    return failures;
}
 
Example 9
Source Project: immutables   Source File: Mirrors.java    License: Apache License 2.0 6 votes vote down vote up
static AttributeTypeKind from(TypeMirror type) {
  if (type.getKind() == TypeKind.DECLARED) {
    TypeElement typeElement = toElement(type);
    if (typeElement.getKind() == ElementKind.ENUM) {
      return ENUM;
    }
    if (typeElement.getKind() == ElementKind.ANNOTATION_TYPE) {
      return ANNOTATION;
    }
    Name qualifiedName = typeElement.getQualifiedName();
    if (qualifiedName.contentEquals(Class.class.getName())) {
      return TYPE;
    }
    if (qualifiedName.contentEquals(String.class.getName())) {
      return STRING;
    }
  } else if (type.getKind().isPrimitive()) {
    return PRIMITIVE;
  }
  throw new AssertionError();
}
 
Example 10
Source Project: firebase-android-sdk   Source File: GetterFactory.java    License: Apache License 2.0 6 votes vote down vote up
/** Returns all getters of a given type. */
public Set<Getter> allGetters(DeclaredType type) {
  if (types.isSameType(type, elements.getTypeElement("java.lang.Object").asType())) {
    return Collections.emptySet();
  }
  Set<Getter> result = new LinkedHashSet<>();
  TypeMirror superclass = ((TypeElement) types.asElement(type)).getSuperclass();

  if (!superclass.getKind().equals(TypeKind.NONE)) {
    result.addAll(allGetters((DeclaredType) superclass));
  }
  for (ExecutableElement method :
      ElementFilter.methodsIn(types.asElement(type).getEnclosedElements())) {
    create(type, method).ifPresent(result::add);
  }
  return result;
}
 
Example 11
Source Project: netbeans   Source File: ResourceStringFoldProvider.java    License: Apache License 2.0 6 votes vote down vote up
private String bundleFileFromClass(TreePath classTreePath, String bfn) {
    TypeMirror tm = info.getTrees().getTypeMirror(classTreePath);
    if (tm.getKind() != TypeKind.DECLARED) {
        return null;
    }
    Element clazz = ((DeclaredType)tm).asElement();
    while ((clazz instanceof TypeElement)) {
        clazz = ((TypeElement)clazz).getEnclosingElement();
    }
    if (clazz.getKind() == ElementKind.PACKAGE) {
        PackageElement pack = ((PackageElement)clazz);
        if (pack.isUnnamed()) {
            return null;
        }
        return pack.getQualifiedName().toString().replaceAll("\\.", "/") + "/" + bfn;
    }
    return null;
}
 
Example 12
Source Project: netbeans   Source File: SpringXMLConfigCompletionItem.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public StringBuilder visitWildcard(WildcardType t, Boolean p) {
    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 {
            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;
}
 
Example 13
Source Project: RetroFacebook   Source File: BuilderSpec.java    License: Apache License 2.0 6 votes vote down vote up
private void addAbstractMethods(
    TypeMirror typeMirror, List<ExecutableElement> abstractMethods) {
  if (typeMirror.getKind() != TypeKind.DECLARED) {
    return;
  }

  TypeElement typeElement = MoreElements.asType(typeMirror.accept(AS_ELEMENT_VISITOR, null));
  addAbstractMethods(typeElement.getSuperclass(), abstractMethods);
  for (TypeMirror interfaceMirror : typeElement.getInterfaces()) {
    addAbstractMethods(interfaceMirror, abstractMethods);
  }
  for (ExecutableElement method : ElementFilter.methodsIn(typeElement.getEnclosedElements())) {
    for (Iterator<ExecutableElement> it = abstractMethods.iterator(); it.hasNext(); ) {
      ExecutableElement maybeOverridden = it.next();
      if (elementUtils.overrides(method, maybeOverridden, typeElement)) {
        it.remove();
      }
    }
    if (method.getModifiers().contains(Modifier.ABSTRACT)) {
      abstractMethods.add(method);
    }
  }
}
 
Example 14
public TypeKind getPrimitiveTypeKind() {
    switch (this) {
    case BOOLEAN:
        return TypeKind.BOOLEAN;
    case BYTE:
        return TypeKind.BYTE;
    case SHORT:
        return TypeKind.SHORT;
    case INT:
        return TypeKind.INT;
    case LONG:
        return TypeKind.LONG;
    case CHAR:
        return TypeKind.CHAR;
    case FLOAT:
        return TypeKind.FLOAT;
    case DOUBLE:
        return TypeKind.DOUBLE;
    case VOID:
        return TypeKind.VOID;
    default:
        throw new AssertionError("unknown primitive type " + this);
    }
}
 
Example 15
Source Project: auto   Source File: MoreElementsTest.java    License: Apache License 2.0 6 votes vote down vote up
private Set<ExecutableElement> visibleMethodsFromObject() {
  Types types = compilation.getTypes();
  TypeMirror intMirror = types.getPrimitiveType(TypeKind.INT);
  TypeMirror longMirror = types.getPrimitiveType(TypeKind.LONG);
  Set<ExecutableElement> methods = new HashSet<ExecutableElement>();
  for (ExecutableElement method : ElementFilter.methodsIn(objectElement.getEnclosedElements())) {
    if (method.getModifiers().contains(Modifier.PUBLIC)
        || method.getModifiers().contains(Modifier.PROTECTED)) {
      methods.add(method);
    }
  }
  assertThat(methods)
      .containsAtLeast(
          getMethod(Object.class, "clone"),
          getMethod(Object.class, "finalize"),
          getMethod(Object.class, "wait"),
          getMethod(Object.class, "wait", longMirror),
          getMethod(Object.class, "wait", longMirror, intMirror));
  return methods;
}
 
Example 16
Source Project: firebase-android-sdk   Source File: GetterFactory.java    License: Apache License 2.0 6 votes vote down vote up
private static Optional<String> inferName(ExecutableElement element) {
  Encodable.Field annotation = element.getAnnotation(Encodable.Field.class);
  if (annotation != null && !annotation.name().isEmpty()) {
    return Optional.of(annotation.name());
  }

  String methodName = element.getSimpleName().toString();
  ExecutableType method = (ExecutableType) element.asType();

  if (methodName.startsWith("is")
      && methodName.length() != 2
      && method.getReturnType().getKind() == TypeKind.BOOLEAN) {
    return Optional.of(Character.toLowerCase(methodName.charAt(2)) + methodName.substring(3));
  }

  if (methodName.startsWith("get")
      && methodName.length() != 3
      && method.getReturnType().getKind() != TypeKind.VOID) {
    return Optional.of(Character.toLowerCase(methodName.charAt(3)) + methodName.substring(4));
  }
  return Optional.empty();
}
 
Example 17
Source Project: netbeans   Source File: CreateElementUtilities.java    License: Apache License 2.0 6 votes vote down vote up
private static List<? extends TypeMirror> computeUnary(Set<ElementKind> types, CompilationInfo info, TreePath parent, Tree error, int offset) {
    UnaryTree tree = (UnaryTree) parent.getLeaf();
    
    if (tree.getExpression() == error) {
        List<? extends TypeMirror> parentTypes = resolveType(types, info, parent.getParentPath(), tree, offset, null, null);
        
        if (parentTypes != null) {
            //may contain only "void", ignore:
            if (parentTypes.size() != 1) {
                return parentTypes;
            }
            if (parentTypes.get(0).getKind() != TypeKind.VOID) {
                return parentTypes;
            }
        }
        
        types.add(ElementKind.PARAMETER);
        types.add(ElementKind.LOCAL_VARIABLE);
        types.add(ElementKind.FIELD);

        return Collections.singletonList(info.getTypes().getPrimitiveType(TypeKind.INT));
    }
    
    return null;
}
 
Example 18
Source Project: java-n-IDE-for-Android   Source File: JCTree.java    License: Apache License 2.0 6 votes vote down vote up
public TypeKind getPrimitiveTypeKind() {
    switch (typetag) {
        case TypeTags.BOOLEAN:
            return TypeKind.BOOLEAN;
        case TypeTags.BYTE:
            return TypeKind.BYTE;
        case TypeTags.SHORT:
            return TypeKind.SHORT;
        case TypeTags.INT:
            return TypeKind.INT;
        case TypeTags.LONG:
            return TypeKind.LONG;
        case TypeTags.CHAR:
            return TypeKind.CHAR;
        case TypeTags.FLOAT:
            return TypeKind.FLOAT;
        case TypeTags.DOUBLE:
            return TypeKind.DOUBLE;
        case TypeTags.VOID:
            return TypeKind.VOID;
        default:
            throw new AssertionError("unknown primitive type " + this);
    }
}
 
Example 19
Source Project: java-n-IDE-for-Android   Source File: Type.java    License: Apache License 2.0 6 votes vote down vote up
public TypeKind getKind() {
    switch (tag) {
    case BYTE:      return TypeKind.BYTE;
    case CHAR:      return TypeKind.CHAR;
    case SHORT:     return TypeKind.SHORT;
    case INT:       return TypeKind.INT;
    case LONG:      return TypeKind.LONG;
    case FLOAT:     return TypeKind.FLOAT;
    case DOUBLE:    return TypeKind.DOUBLE;
    case BOOLEAN:   return TypeKind.BOOLEAN;
    case VOID:      return TypeKind.VOID;
    case BOT:       return TypeKind.NULL;
    case NONE:      return TypeKind.NONE;
    default:        return TypeKind.OTHER;
    }
}
 
Example 20
public NoType getNoType(TypeKind kind)
{
	switch (kind) {
	case NONE:
		return NoTypeImpl.NO_TYPE_NONE;
	case VOID:
		return NoTypeImpl.NO_TYPE_VOID;
	case PACKAGE:
		return NoTypeImpl.NO_TYPE_PACKAGE;
	default:
		throw new IllegalArgumentException();
	}
}
 
Example 21
@Override
protected Problem fastCheckParameters(CompilationController javac) throws IOException {
    Problem result = null;
    String newName = refactoring.getSuperClassName();
    TypeMirror parsedType = javac.getTreeUtilities().parseType(newName, classHandle.resolve(javac));
    if(parsedType != null && parsedType.getKind() != TypeKind.ERROR) {
        result = createProblem(result, true, NbBundle.getMessage(ExtractInterfaceRefactoringPlugin.class, "ERR_ClassClash", newName, pkgName)); // NOI18N
        return result;
    }
    return super.fastCheckParameters(javac);
}
 
Example 22
Source Project: pocketknife   Source File: TypeUtil.java    License: Apache License 2.0 5 votes vote down vote up
private boolean isArrayType(TypeMirror type) {
    if (TypeKind.ARRAY == type.getKind() && type instanceof ArrayType) {
        TypeMirror componentType = ((ArrayType) type).getComponentType();
        return isPrimitive(componentType) || isAggregateType(componentType);
    }
    return false;
}
 
Example 23
Source Project: annotation-tools   Source File: JVMNames.java    License: MIT License 5 votes vote down vote up
/**
 * Create a JVML string for a type.
 * Uses {@link Signatures#binaryNameToFieldDescriptor(String)}
 *
 * Array strings are built by recursively converting the component type.
 *
 * @param type the Type to convert to JVML
 * @return the JVML representation of type
 */
@SuppressWarnings("signature") // com.sun.tools.javac.code is not yet annotated
public static String typeToJvmlString(Type type) {
    if (type.getKind() == TypeKind.ARRAY) {
        return "[" + typeToJvmlString((Type) ((ArrayType) type).getComponentType());
    } else if (type.getKind() == TypeKind.INTERSECTION) {
        // replace w/erasure (== erasure of 1st conjunct)
        return typeToJvmlString(type.tsym.erasure_field);
    } else if (type.getKind() == TypeKind.VOID) {
        return "V";  // special case since UtilPlume doesn't handle void
    } else {
        return Signatures.binaryNameToFieldDescriptor(type.tsym.flatName().toString());
    }
}
 
Example 24
Source Project: jlibs   Source File: VisitorAnnotationProcessor.java    License: Apache License 2.0 5 votes vote down vote up
private void printVisitMethod(String prefix, Map<TypeMirror, ExecutableElement> classes, Printer printer){
    printer.println("@Override");
    printer.println("public Object visit(Object obj){");
    printer.indent++;

    List<TypeMirror> list = new ArrayList<TypeMirror>(classes.keySet());
    Collections.reverse(list);
    boolean addElse = false;
    for(TypeMirror mirror: sort(list)){
        String type = ModelUtil.toString(mirror, true);
        if(addElse)
            printer.print("else ");
        else
            addElse = true;
        printer.println("if(obj instanceof "+type+")");
        printer.indent++;
        if(classes.get(mirror).getReturnType().getKind()!=TypeKind.VOID)
            printer.print("return ");
        printer.println(prefix+METHOD_NAME+"(("+type+")obj);");
        printer.indent--;
    }
    printer.println();
    printer.println("return null;");

    printer.indent--;
    printer.println("}");
}
 
Example 25
Source Project: netbeans   Source File: VarUsageVisitor.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Tree visitMethodInvocation(MethodInvocationTree node, Element p) {
    List<? extends ExpressionTree> arguments = node.getArguments();
    for (int i = 0; i < arguments.size(); i++) {
        ExpressionTree argument = arguments.get(i);
        Element argElement = asElement(argument); // TODO: Slow and misses ternary expressions
        if(p.equals(argElement)) {
            Element element = asElement(node);
            if (element.getKind() == ElementKind.METHOD) {
                ExecutableElement method = (ExecutableElement) element;
                VariableElement parameter = method.getParameters().get(i);
                Types types = workingCopy.getTypes();
                TypeMirror parameterType = parameter.asType();
                if(parameterType.getKind().equals(TypeKind.TYPEVAR)) {
                    TypeVariable typeVariable = (TypeVariable) parameterType;
                    TypeMirror upperBound = typeVariable.getUpperBound();
                    TypeMirror lowerBound = typeVariable.getLowerBound();
                    if(upperBound != null && !types.isSubtype(superTypeElement.asType(), upperBound)) {
                        isReplCandidate = false;
                    }
                    if(lowerBound != null && !types.isSubtype(lowerBound, superTypeElement.asType())) {
                        isReplCandidate = false;
                    }
                } else if(!types.isAssignable(superTypeElement.asType(), parameterType)) {
                    isReplCandidate = false;
                }
            }
        }
    }
    return super.visitMethodInvocation(node, p);
}
 
Example 26
Source Project: requery   Source File: EntityType.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Optional<TypeMirror> builderType() {
    Optional<Entity> entityAnnotation = annotationOf(Entity.class);
    if (entityAnnotation.isPresent()) {
        Entity entity = entityAnnotation.get();
        Elements elements = processingEnvironment.getElementUtils();
        TypeMirror mirror = null;
        try {
            Class<?> builderClass = entity.builder(); // easiest way to get the class TypeMirror
            if (builderClass != void.class) {
                mirror = elements.getTypeElement(builderClass.getName()).asType();
            }
        } catch (MirroredTypeException typeException) {
            mirror = typeException.getTypeMirror();
        }
        if (mirror != null && mirror.getKind() != TypeKind.VOID) {
            return Optional.of(mirror);
        }
    }
    if (builderFactoryMethod().isPresent()) {
        return Optional.of(builderFactoryMethod().get().getReturnType());
    }
    return ElementFilter.typesIn(element().getEnclosedElements()).stream()
            .filter(element -> element.getSimpleName().toString().contains("Builder"))
            .map(Element::asType)
            .filter(Objects::nonNull)
            .filter(type -> type.getKind() != TypeKind.VOID)
            .findFirst();
}
 
Example 27
Source Project: turbine   Source File: TurbineTypesFactoryTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void primitiveTypes() {
  for (TypeKind kind : TypeKind.values()) {
    if (kind.isPrimitive()) {
      PrimitiveType type = turbineTypes.getPrimitiveType(kind);
      assertThat(type.getKind()).isEqualTo(kind);
    } else {
      try {
        turbineTypes.getPrimitiveType(kind);
        fail();
      } catch (IllegalArgumentException expected) {
      }
    }
  }
}
 
Example 28
Source Project: netbeans   Source File: ElementNode.java    License: Apache License 2.0 5 votes vote down vote up
private static String createHtmlHeader(boolean deprecated, ExecutableElement e) {
    StringBuilder sb = new StringBuilder();
    sb.append("<html>");
    if (deprecated) sb.append("<s>");
    if (e.getKind() == ElementKind.CONSTRUCTOR) {
        sb.append(e.getEnclosingElement().getSimpleName());
    } else {
        sb.append(e.getSimpleName());
    }
    if (deprecated) sb.append("</s>");
    sb.append("("); // NOI18N
    for(Iterator<? extends VariableElement> it = e.getParameters().iterator(); it.hasNext(); ) {
        VariableElement param = it.next();
        if (!it.hasNext() && e.isVarArgs() && param.asType().getKind() == TypeKind.ARRAY) {
            sb.append(translateToHTML(print(((ArrayType) param.asType()).getComponentType())));
            sb.append("...");
        } else {
            sb.append(translateToHTML(print(param.asType())));
        }
        sb.append(" "); // NOI18N
        sb.append(param.getSimpleName());
        if (it.hasNext()) {
            sb.append(", "); // NOI18N
        }
    }
    sb.append(")"); // NOI18N
    if ( e.getKind() != ElementKind.CONSTRUCTOR ) {
        TypeMirror rt = e.getReturnType();
        if ( rt.getKind() != TypeKind.VOID ) {
            sb.append(" : "); // NOI18N
            sb.append(translateToHTML(print(e.getReturnType())));
        }
    }
    return sb.toString();
}
 
Example 29
Source Project: netbeans   Source File: IfToSwitchSupport.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Evaluates the constant. The method should return a constant value, possibly wrapped
 * if the value is primitive. It may return an encapsulated constant, with well-defned
 * equals/hashcode. The value is just compared and {@link #convert}ed. <p/>
 * Returns {@code null} if the path is not a compile-time constant.
 * @param path
 * @return constant value.
 */
protected Object evalConstant(TreePath path) {
    TypeMirror m = ci.getTrees().getTypeMirror(path);
    if (m != null && m.getKind() != TypeKind.DECLARED) {
        return ArithmeticUtilities.compute(ci, path, true, true);
    }
    Element e = ci.getTrees().getElement(path);
    if (e != null && e.getKind() == ElementKind.ENUM_CONSTANT) {
        return new EnumConst(e);
    }
    return null;
}
 
Example 30
Source Project: netbeans   Source File: TreeUtilities.java    License: Apache License 2.0 5 votes vote down vote up
public Void visitMethod(MethodTree node, Set<TypeMirror> p) {
    Set<TypeMirror> s = new LinkedHashSet<TypeMirror>();
    scan(node.getBody(), s);
    for (ExpressionTree et : node.getThrows()) {
        TypeMirror t = info.getTrees().getTypeMirror(new TreePath(getCurrentPath(), et));
        if (t != null && t.getKind() != TypeKind.ERROR) {
            for (Iterator<TypeMirror> it = s.iterator(); it.hasNext();)
                if (info.getTypes().isSubtype(it.next(), t))
                    it.remove();
        }
    }
    p.addAll(s);
    return null;
}