Java Code Examples for javax.lang.model.element.TypeElement.getTypeParameters()

The following are Jave code examples for showing how to use getTypeParameters() of the javax.lang.model.element.TypeElement class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
Example 1
Project: GitHub   File: PresenterInjectorRules.java   Source Code and License Vote up 6 votes
private Map<TypeParameterElement, TypeMirror> getChildInstanceOfClassFromGeneric(final TypeElement typeElement, final Class<?> aClass) {
	Map<TypeParameterElement, TypeMirror> result = new HashMap<>();
	for (TypeParameterElement element : typeElement.getTypeParameters()) {
		List<? extends TypeMirror> bounds = element.getBounds();
		for (TypeMirror bound : bounds) {
			if (bound instanceof DeclaredType && ((DeclaredType) bound).asElement() instanceof TypeElement) {
				Collection<TypeMirror> viewsType = getViewsType((TypeElement) ((DeclaredType) bound).asElement());
				boolean isViewType = false;
				for (TypeMirror viewType : viewsType) {
					if (((DeclaredType) viewType).asElement().toString().equals(aClass.getCanonicalName())) {
						isViewType = true;
					}
				}

				if (isViewType) {
					result.put(element, bound);
					break;
				}
			}
		}
	}

	return result;
}
 
Example 2
Project: GitHub   File: TypeHierarchyCollector.java   Source Code and License Vote up 6 votes
TypevarContext(TypeElement element, String renderedTypeString) {
  List<? extends TypeParameterElement> typeParameters = element.getTypeParameters();
  if (!typeParameters.isEmpty()) {
    this.arguments = SourceTypes.extract(renderedTypeString).getValue();

    this.parameters = Lists.newArrayList();
    for (TypeParameterElement p : typeParameters) {
      parameters.add(p.getSimpleName().toString());
    }
    // we allow having no arguments in a string as raw type/unspecified argument scenario
    Verify.verify(arguments.isEmpty() || (parameters.size() == arguments.size()), parameters + " =/> " + arguments);
  } else {
    this.parameters = Collections.emptyList();
    this.arguments = Collections.emptyList();
  }
}
 
Example 3
Project: incubator-netbeans   File: JavadocImports.java   Source Code and License Vote up 6 votes
private static Element paramElementFor(Element methodOrClass, ParamTree ptag) {
    ElementKind kind = methodOrClass.getKind();
    List<? extends Element> params = Collections.emptyList();
    if (kind == ElementKind.METHOD || kind == ElementKind.CONSTRUCTOR) {
        ExecutableElement ee = (ExecutableElement) methodOrClass;
        params = ptag.isTypeParameter()
                ? ee.getTypeParameters()
                : ee.getParameters();
    } else if (kind.isClass() || kind.isInterface()) {
        TypeElement te = (TypeElement) methodOrClass;
        params = te.getTypeParameters();
    }

    for (Element param : params) {
        if (param.getSimpleName().contentEquals(ptag.getName().getName())) {
            return param;
        }
    }
    return null;
}
 
Example 4
Project: incubator-netbeans   File: ExportNonAccessibleElement.java   Source Code and License Vote up 6 votes
public Boolean visitType(TypeElement arg0, Void arg1) {
    for (TypeParameterElement e : arg0.getTypeParameters()) {
        if (stop) {
            return false;
        }
        
        for (TypeMirror b : e.getBounds()) {
            if (stop) {
                return false;
            }
            
            if (b.accept(this, arg1)) {
                return true;
            }
        }
    }

    TypeMirror superclass = arg0.getSuperclass();
    if (superclass.getKind() == TypeKind.DECLARED) {
        if (!((DeclaredType) superclass).asElement().getKind().isInterface()) {
            return false;
        }
    }

    return superclass.accept(this, arg1);
}
 
Example 5
Project: incubator-netbeans   File: JavadocGenerator.java   Source Code and License Vote up 6 votes
public String generateComment(TypeElement clazz, CompilationInfo javac) {
        StringBuilder builder = new StringBuilder(
//                "/**\n" + // NOI18N
                "\n" // NOI18N
                );
        
        if (clazz.getNestingKind() == NestingKind.TOP_LEVEL) {
            builder.append("@author ").append(author).append("\n"); // NOI18N
        }
        
        if (SourceVersion.RELEASE_5.compareTo(srcVersion) <= 0) {
            for (TypeParameterElement param : clazz.getTypeParameters()) {
                builder.append("@param <").append(param.getSimpleName().toString()).append("> \n"); // NOI18N
            }
        }
        
        if (SourceVersion.RELEASE_5.compareTo(srcVersion) <= 0 &&
                JavadocUtilities.isDeprecated(javac, clazz)) {
            builder.append("@deprecated\n"); // NOI18N
        }
        
//        builder.append("*/\n"); // NOI18N

        return builder.toString();
    }
 
Example 6
Project: dataenum   File: SpecParser.java   Source Code and License Vote up 6 votes
public static Spec parse(Element element, ProcessingEnvironment processingEnv) {
  Messager messager = processingEnv.getMessager();

  if (element.getKind() != ElementKind.INTERFACE) {
    messager.printMessage(
        Diagnostic.Kind.ERROR, "@DataEnum can only be used on interfaces.", element);
    return null;
  }

  TypeElement dataEnum = (TypeElement) element;

  List<TypeVariableName> typeVariableNames = new ArrayList<>();
  for (TypeParameterElement typeParameterElement : dataEnum.getTypeParameters()) {
    typeVariableNames.add(TypeVariableName.get(typeParameterElement));
  }

  List<Value> values = ValuesParser.parse(dataEnum, processingEnv);
  if (values == null) {
    return null;
  }

  ClassName enumInterface = ClassName.get(dataEnum);
  return new Spec(enumInterface, typeVariableNames, values);
}
 
Example 7
Project: openjdk-jdk10   File: ElementStructureTest.java   Source Code and License Vote up 6 votes
void writeType(TypeElement e) {
    if (!acceptType.test(task.getElements().getBinaryName(e).toString()))
        return ;
    try {
        analyzeElement(e);
        writeTypes(e.getInterfaces());
        out.write(e.getNestingKind().toString());
        out.write(e.getQualifiedName().toString());
        write(e.getSuperclass());
        for (TypeParameterElement param : e.getTypeParameters()) {
            visit(param, null);
        }
        List<Element> defs = new ArrayList<>(e.getEnclosedElements()); //XXX: forcing ordering for members - not completely correct!
        Collections.sort(defs, (e1, e2) -> e1.toString().compareTo(e2.toString()));
        for (Element def : defs) {
            visit(def, null);
        }
        out.write("\n");
    } catch (IOException ex) {
        ex.printStackTrace();
    }
}
 
Example 8
Project: GitHub   File: ViewStateProviderClassGenerator.java   Source Code and License Vote up 5 votes
private String getViewClassFromGeneric(TypeElement typeElement) {
	TypeMirror superclass = typeElement.asType();

	Map<String, String> parentTypes = Collections.emptyMap();

	if (!typeElement.getTypeParameters().isEmpty()) {
		MvpCompiler.getMessager().printMessage(Diagnostic.Kind.WARNING, "Your " + typeElement.getSimpleName() + " is typed. @InjectViewState may generate wrong code. Your can set view/view state class manually.");
	}

	while (superclass.getKind() != TypeKind.NONE) {
		TypeElement superclassElement = (TypeElement) ((DeclaredType) superclass).asElement();

		final List<? extends TypeMirror> typeArguments = ((DeclaredType) superclass).getTypeArguments();
		final List<? extends TypeParameterElement> typeParameters = superclassElement.getTypeParameters();

		if (typeArguments.size() > typeParameters.size()) {
			throw new IllegalArgumentException("Code generation for interface " + typeElement.getSimpleName() + " failed. Simplify your generics. (" + typeArguments + " vs " + typeParameters + ")");
		}

		Map<String, String> types = new HashMap<>();
		for (int i = 0; i < typeArguments.size(); i++) {
			types.put(typeParameters.get(i).toString(), fillGenerics(parentTypes, typeArguments.get(i)));
		}

		if (superclassElement.toString().equals(MVP_PRESENTER_CLASS)) {
			// MvpPresenter is typed only on View class
			return fillGenerics(parentTypes, typeArguments);
		}

		parentTypes = types;

		superclass = superclassElement.getSuperclass();
	}

	return "";
}
 
Example 9
Project: autojackson   File: ImplementationCreator.java   Source Code and License Vote up 5 votes
/**
 * A Helper method for {@link #loadMethodDetails(TypeElement)} which does the hard work of actually
 * checking the types for the parents.
 *
 * @param declaredType The DeclaredType object for the interface which has the method
 * @param method       The method checking for types on
 * @return A method detail, either with the Generic return type, or the default return type
 */
private MethodDetail checkParentMethod(DeclaredType declaredType, ExecutableElement method) {
    // check to see if we have any type parameters at all, if we don't then we can just create
    // the standard method
    TypeElement typeElement = (TypeElement) (declaredType).asElement();
    List<? extends TypeParameterElement> typeParameters = typeElement.getTypeParameters();
    if (typeParameters.isEmpty()) {
        new MethodDetail(method);
    }

    // otherwise we need to check if our return type is actually one of our generic parameters
    // first we need to check if our method return type matches one of our Type Parameters
    Optional<? extends TypeParameterElement> element = typeParameters.stream()
            .filter(parameterElement -> parameterElement.asType().getKind().equals(method.getReturnType().getKind()))
            .findFirst();

    return element.map(matchingType -> {
        final List<? extends TypeMirror> typeArguments = declaredType.getTypeArguments();
        final int parameterIndex = typeParameters.indexOf(matchingType);
        final TypeMirror returnType;

        if (typeArguments.size() > parameterIndex) {
            returnType = typeArguments.get(parameterIndex);
        } else {
            returnType = ((TypeVariable) matchingType.asType()).getUpperBound();
        }

        return new MethodDetail(method, Optional.of(returnType));
    }).orElse(new MethodDetail(method));
}
 
Example 10
Project: auto-value-step-builder   File: TypeSimplifier.java   Source Code and License Vote up 5 votes
String formalTypeParametersString(TypeElement type) {
  List<? extends TypeParameterElement> typeParameters = type.getTypeParameters();
  if (typeParameters.isEmpty()) {
    return "";
  } else {
    StringBuilder sb = new StringBuilder("<");
    String sep = "";
    for (TypeParameterElement typeParameter : typeParameters) {
      sb.append(sep);
      sep = ", ";
      appendTypeParameterWithBounds(sb, typeParameter);
    }
    return sb.append(">").toString();
  }
}
 
Example 11
Project: GitHub   File: ViewStateClassGenerator.java   Source Code and License Vote up 5 votes
private List<Method> iterateInterfaces(int level, TypeElement parentElement, String parentDefaultStrategy, Map<String, String> parentTypes, List<Method> rootMethods, List<Method> superinterfacesMethods) {
	for (TypeMirror typeMirror : parentElement.getInterfaces()) {
		final TypeElement anInterface = (TypeElement) ((DeclaredType) typeMirror).asElement();

		final List<? extends TypeMirror> typeArguments = ((DeclaredType) typeMirror).getTypeArguments();
		final List<? extends TypeParameterElement> typeParameters = anInterface.getTypeParameters();

		if (typeArguments.size() > typeParameters.size()) {
			throw new IllegalArgumentException("Code generation for interface " + anInterface.getSimpleName() + " failed. Simplify your generics.");
		}

		Map<String, String> types = new HashMap<>();
		for (int i = 0; i < typeArguments.size(); i++) {
			types.put(typeParameters.get(i).toString(), typeArguments.get(i).toString());
		}

		Map<String, String> totalInterfaceTypes = new HashMap<>(typeParameters.size());
		for (int i = 0; i < typeArguments.size(); i++) {
			totalInterfaceTypes.put(typeParameters.get(i).toString(), fillGenerics(parentTypes, typeArguments.get(i)));
		}
		for (int i = typeArguments.size(); i < typeParameters.size(); i++) {
			if (typeParameters.get(i).getBounds().size() != 1) {
				throw new IllegalArgumentException("Code generation for interface " + anInterface.getSimpleName() + " failed. Simplify your generics.");
			}

			totalInterfaceTypes.put(typeParameters.get(i).toString(), typeParameters.get(i).getBounds().get(0).toString());
		}

		String defaultStrategy = parentDefaultStrategy != null ? parentDefaultStrategy : getStateStrategyType(anInterface);

		getMethods(totalInterfaceTypes, anInterface, defaultStrategy, rootMethods, superinterfacesMethods);

		iterateInterfaces(level + 1, anInterface, defaultStrategy, types, rootMethods, superinterfacesMethods);
	}

	return superinterfacesMethods;
}
 
Example 12
Project: incubator-netbeans   File: ElementUtilities.java   Source Code and License Vote up 5 votes
private DeclaredType getDeclaredType(TypeElement e, HashMap<? extends Element, ? extends TypeMirror> map, Types types) {
    List<? extends TypeParameterElement> tpes = e.getTypeParameters();
    TypeMirror[] targs = new TypeMirror[tpes.size()];
    int i = 0;
    for (Iterator<? extends TypeParameterElement> it = tpes.iterator(); it.hasNext();) {
        TypeParameterElement tpe = it.next();
        TypeMirror t = map.get(tpe);
        targs[i++] = t != null ? t : tpe.asType();
    }
    Element encl = e.getEnclosingElement();
    if ((encl.getKind().isClass() || encl.getKind().isInterface()) && !((TypeElement)encl).getTypeParameters().isEmpty())
            return types.getDeclaredType(getDeclaredType((TypeElement)encl, map, types), e, targs);
    return types.getDeclaredType(e, targs);
}
 
Example 13
Project: incubator-netbeans   File: JavadocCompletionQuery.java   Source Code and License Vote up 5 votes
private DeclaredType getDeclaredType(TypeElement e, HashMap<? extends Element, ? extends TypeMirror> map, Types types) {
    List<? extends TypeParameterElement> tpes = e.getTypeParameters();
    TypeMirror[] targs = new TypeMirror[tpes.size()];
    int i = 0;
    for (Iterator<? extends TypeParameterElement> it = tpes.iterator(); it.hasNext();) {
        TypeParameterElement tpe = it.next();
        TypeMirror t = map.get(tpe);
        targs[i++] = t != null ? t : tpe.asType();
    }
    Element encl = e.getEnclosingElement();
    if ((encl.getKind().isClass() || encl.getKind().isInterface()) && !((TypeElement)encl).getTypeParameters().isEmpty())
            return types.getDeclaredType(getDeclaredType((TypeElement)encl, map, types), e, targs);
    return types.getDeclaredType(e, targs);
}
 
Example 14
Project: incubator-netbeans   File: ElementNode.java   Source Code and License Vote up 5 votes
private static String createHtmlHeader(boolean deprecated, TypeElement e) {
    StringBuilder sb = new StringBuilder();
    sb.append("<html>");
    if (deprecated) sb.append("<s>");
    sb.append(e.getSimpleName());
    if (deprecated) sb.append("</s>");
    List<? extends TypeParameterElement> typeParams = e.getTypeParameters();
    if (typeParams != null && !typeParams.isEmpty()) {
        sb.append("&lt;"); // NOI18N
        for(Iterator<? extends TypeParameterElement> it = typeParams.iterator(); it.hasNext();) {
            TypeParameterElement tp = it.next();
            sb.append(tp.getSimpleName());
            try {
                List<? extends TypeMirror> bounds = tp.getBounds();
                if (!bounds.isEmpty()) {
                    sb.append(translateToHTML(printBounds(bounds)));
                }
            }
            catch (NullPointerException npe) {
            }                    
            if (it.hasNext()) {
                sb.append(", "); // NOI18N
            }
        }
        sb.append("&gt;"); // NOI18N
    }
    return sb.toString();
}
 
Example 15
Project: auto-value-step-builder   File: TypeSimplifier.java   Source Code and License Vote up 5 votes
static String actualTypeParametersString(TypeElement type) {
  List<? extends TypeParameterElement> typeParameters = type.getTypeParameters();
  if (typeParameters.isEmpty()) {
    return "";
  } else {
    return typeParameters.stream()
        .map(e -> e.getSimpleName().toString())
        .collect(joining(", ", "<", ">"));
  }
}
 
Example 16
Project: auto-value-node   File: TypeSimplifier.java   Source Code and License Vote up 5 votes
String formalTypeParametersString(TypeElement type) {
    List<? extends TypeParameterElement> typeParameters = type.getTypeParameters();
    if (typeParameters.isEmpty()) {
        return "";
    } else {
        StringBuilder sb = new StringBuilder("<");
        String sep = "";
        for (TypeParameterElement typeParameter : typeParameters) {
            sb.append(sep);
            sep = ", ";
            appendTypeParameterWithBounds(sb, typeParameter);
        }
        return sb.append(">").toString();
    }
}
 
Example 17
Project: auto-value-node   File: TypeSimplifier.java   Source Code and License Vote up 5 votes
static String actualTypeParametersString(TypeElement type) {
    List<? extends TypeParameterElement> typeParameters = type.getTypeParameters();
    if (typeParameters.isEmpty()) {
        return "";
    } else {
        return "<"
                + FluentIterable.from(typeParameters)
                .transform(SimpleNameFunction.INSTANCE)
                .join(Joiner.on(", "))
                + ">";
    }
}
 
Example 18
Project: openjdk-jdk10   File: Utils.java   Source Code and License Vote up 5 votes
/**
 * 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;
}
 
Example 19
Project: incubator-netbeans   File: ElementJavadoc.java   Source Code and License Vote up 4 votes
private StringBuilder getClassHeader(TypeElement cdoc) {
    StringBuilder sb = new StringBuilder();
    sb.append("<pre>"); //NOI18N
    cdoc.getAnnotationMirrors().forEach((annotationDesc) -> {
        appendAnnotation(sb, annotationDesc, true);
    });
    for (Modifier modifier : cdoc.getModifiers()) {
        switch(cdoc.getKind()) {
            case ENUM:
                if (modifier == Modifier.FINAL)
                    continue;
                break;
            case INTERFACE:
            case ANNOTATION_TYPE:
                if (modifier == Modifier.ABSTRACT)
                    continue;
                break;                     
        }
        sb.append(modifier).append(' '); //NOI18N
    }
    switch (cdoc.getKind()) {
        case ANNOTATION_TYPE:
            sb.append("@interface "); //NOI18N
            break;
        case ENUM:
            sb.append("enum "); //NOI18N
            break;
        case INTERFACE:
            sb.append("interface "); //NOI18N
            break;
        default:
            sb.append("class "); //NOI18N            
    }
    sb.append("<b>").append(cdoc.getSimpleName()); //NOI18N
    List<? extends TypeParameterElement> typeParams = cdoc.getTypeParameters();
    if (!typeParams.isEmpty()) {
        sb.append("&lt;"); //NOI18N
        for (Iterator<? extends TypeParameterElement> it = typeParams.iterator(); it.hasNext();) {
            TypeParameterElement typeParam = it.next();
            appendType(sb, typeParam.asType(), false, true, false);
            if (it.hasNext())
                sb.append(","); //NOI18N
        }
        sb.append("&gt;"); //NOI18N
    }
    sb.append("</b>"); //NOi18N
    if (cdoc.getKind() != ElementKind.ANNOTATION_TYPE) {
        TypeMirror supercls = cdoc.getSuperclass();
        if (supercls != null && supercls.getKind() != TypeKind.NONE) {
            sb.append("<br>extends "); //NOI18N
            appendType(sb, supercls, false, false, false);            
        }
        List<? extends TypeMirror> ifaces = cdoc.getInterfaces();
        if (!ifaces.isEmpty()) {
            sb.append(cdoc.getKind().isInterface() ? "<br>extends " : "<br>implements "); //NOI18N
            for (Iterator<? extends TypeMirror> it = ifaces.iterator(); it.hasNext();) {
                TypeMirror iface = it.next();
                appendType(sb, iface, false, false, false);
                if (it.hasNext())
                    sb.append(", "); //NOI18N
            }            
        }
    }
    sb.append("</pre>"); //NOI18N
    return sb;
}
 
Example 20
Project: inspector   File: InspectorProcessor.java   Source Code and License Vote up 4 votes
private void generateClass(TypeElement targetClass) {

    Map<String, ExecutableElement> propertiesMap = getProperties(targetClass);
    List<Property> properties = readProperties(propertiesMap);

    List<? extends TypeParameterElement> typeParams = targetClass.getTypeParameters();
    boolean shouldCreateGenerics = typeParams != null && typeParams.size() > 0;

    String packageName = elements.getPackageOf(targetClass)
        .getQualifiedName()
        .toString();
    String simpleName = targetClass.getSimpleName()
        .toString();

    ClassName targetClassName = ClassName.get(targetClass);
    TypeVariableName[] genericTypeNames = null;

    if (shouldCreateGenerics) {
      genericTypeNames = new TypeVariableName[typeParams.size()];
      for (int i = 0; i < typeParams.size(); i++) {
        genericTypeNames[i] = TypeVariableName.get(typeParams.get(i));
      }
    }

    TypeSpec.Builder validator =
        createValidator(simpleName, targetClassName, genericTypeNames, properties);

    if (shouldCreateGenerics) {
      validator.addTypeVariables(Arrays.asList(genericTypeNames));
    }

    validator.addModifiers(FINAL);

    try {
      JavaFile.builder(packageName, validator.build())
          .skipJavaLangImports(true)
          .build()
          .writeTo(filer);
    } catch (IOException e) {
      throw new RuntimeException(e);
    }
  }