下面列出了javax.lang.model.element.VariableElement#asType ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* See {@link #matchesArrayListClass(VariableElement, Class, MatchPolicy)}.
*/
private boolean matchesArrayListClass(VariableElement field, String className, MatchPolicy policy) {
if (!(field.asType() instanceof DeclaredType)) {
return false;
}
// Get generic information
DeclaredType declaredType = (DeclaredType) field.asType();
// Check general form
if (declaredType.getTypeArguments().size() != 1) {
return false;
}
// Ensure that outer type is ArrayList
TypeElement arrayList = getTypeElementForClass(ArrayList.class);
TypeMirror erased = environment.getTypeUtils().erasure(declaredType);
boolean isArrayList = typesMatch(erased, arrayList.asType(), MatchPolicy.ASSIGNABLE);
// Make sure inner type matches
TypeMirror innerType = declaredType.getTypeArguments().get(0);
TypeElement target = getTypeElementForClass(className);
boolean innerTypeMatches = target != null && typesMatch(innerType, target.asType(), policy);
return isArrayList && innerTypeMatches;
}
private static void checkDatasourceField(TypeElement typeElement, String name) {
List<VariableElement> elements = ElementFilter.fieldsIn(typeElement.getEnclosedElements());
VariableElement variableElement = elements.get(0);
assertTrue(variableElement.getSimpleName().contentEquals(name)); // field name
DeclaredType declaredType = (DeclaredType) variableElement.asType();
TypeElement returnTypeElement = (TypeElement) declaredType.asElement();
assertTrue(returnTypeElement.getQualifiedName().contentEquals("javax.sql.DataSource")); // field type
AnnotationMirror annotationMirror = variableElement.getAnnotationMirrors().get(0);
DeclaredType annotationDeclaredType = annotationMirror.getAnnotationType();
TypeElement annotationTypeElement = (TypeElement) annotationDeclaredType.asElement();
assertTrue(annotationTypeElement.getQualifiedName().contentEquals("javax.annotation.Resource")); // annotation type
Map.Entry<? extends ExecutableElement, ? extends AnnotationValue> entry = annotationMirror.getElementValues().entrySet().iterator().next();
String attributeName = entry.getKey().getSimpleName().toString();
String attributeValue = (String) entry.getValue().getValue();
assertEquals("name", attributeName); // attributes
assertEquals(name, attributeValue);
}
public static TypeMirror getHolderValueType(TypeMirror type, TypeElement defHolder, ProcessingEnvironment env) {
TypeElement typeElement = getDeclaration(type);
if (typeElement == null)
return null;
if (isSubElement(typeElement, defHolder)) {
if (type.getKind().equals(TypeKind.DECLARED)) {
Collection<? extends TypeMirror> argTypes = ((DeclaredType) type).getTypeArguments();
if (argTypes.size() == 1) {
return argTypes.iterator().next();
} else if (argTypes.isEmpty()) {
VariableElement member = getValueMember(typeElement);
if (member != null) {
return member.asType();
}
}
}
}
return null;
}
public JavadocExecutableItem(CompletionItem jmethod,
ExecutableElement ee, int substitutionOffset) {
this.delegate = jmethod;
this.substitutionOffset = substitutionOffset;
this.name = ee.getKind() == ElementKind.METHOD
? ee.getSimpleName()
: ee.getEnclosingElement().getSimpleName();
List<? extends VariableElement> params = ee.getParameters();
this.paramTypes = new String[params.size()];
int i = 0;
for (VariableElement p : params) {
TypeMirror asType = p.asType();
this.paramTypes[i++] = resolveTypeName(asType, ee.isVarArgs()).toString();
}
}
public String makeSignature(ExecutableElement e, boolean full, boolean ignoreTypeParameters) {
StringBuilder result = new StringBuilder();
result.append("(");
Iterator<? extends VariableElement> iterator = e.getParameters().iterator();
while (iterator.hasNext()) {
VariableElement next = iterator.next();
TypeMirror type = next.asType();
result.append(getTypeSignature(type, full, ignoreTypeParameters));
if (iterator.hasNext()) {
result.append(", ");
}
}
if (e.isVarArgs()) {
int len = result.length();
result.replace(len - 2, len, "...");
}
result.append(")");
return result.toString();
}
public String buildCallbackType(ExecutableElement method) {
Types typeUtils = processingEnv.getTypeUtils();
TypeMirror callback = getTypeMirror(processingEnv, RetroWeibo.Callback.class);
List<? extends VariableElement> parameters = method.getParameters();
for (VariableElement parameter : parameters) {
TypeMirror type = parameter.asType();
if (type instanceof DeclaredType) {
List<? extends TypeMirror> params = ((DeclaredType) type).getTypeArguments();
if (params.size() == 1) {
callback = typeUtils.getDeclaredType((TypeElement) typeUtils
.asElement(callback), new TypeMirror[] {params.get(0)});
if (typeUtils.isSubtype(type, callback)) {
return typeSimplifier.simplify(params.get(0));
}
}
}
}
return "";
}
@Override
protected void setScope( WebBeansModel model, Element element ){
TypeElement clazz = (TypeElement)element;
List<VariableElement> fields = ElementFilter.fieldsIn(
model.getCompilationController().getElements().getAllMembers( clazz));
VariableElement delegate = null;
for (VariableElement field : fields) {
if( hasDelegate(field, model.getCompilationController())){
delegate = field;
break;
}
}
TypeMirror delegateType = delegate.asType();
StringBuilder shortName = new StringBuilder();
StringBuilder fqnName = new StringBuilder();
fillElementType(delegateType, shortName, fqnName, model.getCompilationController());
JEditorPane scopeComponent = getScopeComponent();
if ( showFqns() ){
scopeComponent.setText( fqnName.toString() );
}
else {
scopeComponent.setText( shortName.toString() );
}
}
public void addObjectToDbValueMethod(ExecutableElement method) {
final TypeElement enclosingElement = (TypeElement) method.getEnclosingElement();
this.objectToDbValueMethod = method;
this.serializedTypeTransformerElement = enclosingElement;
this.serializedTypeTransformerClassName = ClassName.get(enclosingElement);
if (!hasDbToObject) {
final VariableElement firstParam = method.getParameters().get(0);
rawDeserializedType = firstParam.asType();
deserializedType = environment.getAnyTypeElement(rawDeserializedType);
rawSerializedType = method.getReturnType();
serializedType = environment.getSupportedSerializedTypeElement(rawSerializedType);
}
hasObjectToDb = true;
}
public void testIsCastingUnchecked() {
TypeElement erasureClass = typeElementOf("Erasure");
List<VariableElement> fields = ElementFilter.fieldsIn(erasureClass.getEnclosedElements());
for (VariableElement field : fields) {
String fieldName = field.getSimpleName().toString();
boolean expectUnchecked;
if (fieldName.endsWith("Yes")) {
expectUnchecked = true;
} else if (fieldName.endsWith("No")) {
expectUnchecked = false;
} else {
throw new AssertionError("Fields in Erasure class must end with Yes or No: " + fieldName);
}
TypeMirror fieldType = field.asType();
boolean actualUnchecked = TypeSimplifier.isCastingUnchecked(fieldType);
assertEquals("Unchecked-cast status for " + fieldType, expectUnchecked, actualUnchecked);
}
}
/**
* Test if variable element is event injection point.
*
* @param element element for check
* @return true if element is event injection point
*/
public boolean isEventInjectionPoint( VariableElement element )
{
TypeMirror elementType = element.asType();
Element typeElement = getCompilationController().
getTypes().asElement( elementType);
if ( typeElement instanceof TypeElement ){
String typeElementFqn = ((TypeElement)typeElement).getQualifiedName().
toString();
if ( WebBeansModelProviderImpl.EVENT_INTERFACE.equals( typeElementFqn )){
try {
return isInjectionPoint(element);
}
catch(InjectionPointDefinitionError e ){
return false;
}
}
}
return false;
}
public static TypeMirror getHolderValueType(TypeMirror type, TypeElement defHolder, ProcessingEnvironment env) {
TypeElement typeElement = getDeclaration(type);
if (typeElement == null)
return null;
if (isSubElement(typeElement, defHolder)) {
if (type.getKind().equals(TypeKind.DECLARED)) {
Collection<? extends TypeMirror> argTypes = ((DeclaredType) type).getTypeArguments();
if (argTypes.size() == 1) {
return argTypes.iterator().next();
} else if (argTypes.isEmpty()) {
VariableElement member = getValueMember(typeElement);
if (member != null) {
return member.asType();
}
}
}
}
return null;
}
protected boolean isAsync(Element method){
if ( method instanceof ExecutableElement ){
ExecutableElement exec = (ExecutableElement)method;
List<? extends VariableElement> parameters = exec.getParameters();
for (VariableElement param : parameters) {
boolean hasAsyncType = false;
TypeMirror type = param.asType();
if ( type instanceof DeclaredType ){
Element paramElement = ((DeclaredType)type).asElement();
if ( paramElement instanceof TypeElement ){
hasAsyncType = ((TypeElement)paramElement).getQualifiedName().
contentEquals("javax.ws.rs.container.AsyncResponse"); // NOI18N
}
}
if( hasAsyncType && hasAnnotation(param,
"javax.ws.rs.container.Suspended")){ // NOI18N
return true;
}
}
}
return false;
}
@Override
public List<? extends CodeGenerator> create(Lookup context) {
ArrayList<CodeGenerator> ret = new ArrayList<>();
JTextComponent component = context.lookup(JTextComponent.class);
CompilationController controller = context.lookup(CompilationController.class);
if (component == null || controller == null) {
return ret;
}
TreePath path = context.lookup(TreePath.class);
path = controller.getTreeUtilities().getPathElementOfKind(TreeUtilities.CLASS_TREE_KINDS, path);
if (path == null) {
return ret;
}
try {
controller.toPhase(JavaSource.Phase.ELEMENTS_RESOLVED);
} catch (IOException ioe) {
return ret;
}
TypeElement typeElement = (TypeElement) controller.getTrees().getElement(path);
if (typeElement == null || !typeElement.getKind().isClass()) {
return ret;
}
for (VariableElement ve : ElementFilter.fieldsIn(typeElement.getEnclosedElements())) {
TypeMirror type = ve.asType();
if (type.getKind() == TypeKind.DECLARED && ((TypeElement)((DeclaredType)type).asElement()).getQualifiedName().contentEquals(Logger.class.getName())) {
return ret;
}
}
List<ElementNode.Description> descriptions = new ArrayList<>();
ret.add(new LoggerGenerator(component, ElementNode.Description.create(controller, typeElement, descriptions, false, false)));
return ret;
}
private String getAssignmentFunctionName(
Assignment node, VariableElement var, boolean isRetainedWith) {
if (!ElementUtil.isField(var)) {
return null;
}
TypeMirror type = var.asType();
boolean isPrimitive = type.getKind().isPrimitive();
boolean isStrong = !isPrimitive && !ElementUtil.isWeakReference(var);
boolean isVolatile = ElementUtil.isVolatile(var);
if (isRetainedWith) {
return isVolatile ? "JreVolatileRetainedWithAssign" : "JreRetainedWithAssign";
}
if (isVolatile) {
// We can't use the "AndConsume" optimization for volatile objects because that might leave
// the newly created object vulnerable to being deallocated by another thread assigning to the
// same field.
return isStrong ? "JreVolatileStrongAssign" : "JreAssignVolatile"
+ (isPrimitive ? NameTable.capitalize(TypeUtil.getName(type)) : "Id");
}
if (isStrong && options.useReferenceCounting()) {
String funcName = "JreStrongAssign";
Expression retainedRhs = TranslationUtil.retainResult(node.getRightHandSide());
if (retainedRhs != null) {
funcName += "AndConsume";
node.setRightHandSide(retainedRhs);
}
return funcName;
}
return null;
}
private void checkMethodParameters(Set<TypeElement> classes) {
Types types = processingEnv.getTypeUtils();
for (TypeElement te: classes) {
for (ExecutableElement ee: ElementFilter.methodsIn(te.getEnclosedElements())) {
for (VariableElement ve: ee.getParameters()) {
TypeMirror tm = ve.asType();
checkMethodParametersVisitor.visit(tm, types);
}
}
}
}
public TypeMirror getFieldType(VariableElement f) {
return f.asType();
}
public TypeMirror getFieldType(VariableElement f) {
return f.asType();
}
private ImmutableList<TypeMirror> getAcceptedConverterReturnTypes(VariableElement optionField)
throws OptionProcessorException {
TypeMirror optionType = optionField.asType();
Option annotation = optionField.getAnnotation(Option.class);
TypeMirror listType = elementUtils.getTypeElement(List.class.getCanonicalName()).asType();
// Options that accumulate multiple mentions in an arglist must have type List<T>, where each
// individual mention has type T. Identify type T to use it for checking the converter's return
// type.
if (annotation.allowMultiple()) {
// Check that the option type is in fact a list.
if (optionType.getKind() != TypeKind.DECLARED) {
throw new OptionProcessorException(
optionField,
"Option that allows multiple occurrences must be of type %s, but is of type %s",
listType,
optionType);
}
DeclaredType optionDeclaredType = (DeclaredType) optionType;
// optionDeclaredType.asElement().asType() gets us from List<actualType> to List<E>, so this
// is unfortunately necessary.
if (!typeUtils.isAssignable(optionDeclaredType.asElement().asType(), listType)) {
throw new OptionProcessorException(
optionField,
"Option that allows multiple occurrences must be of type %s, but is of type %s",
listType,
optionType);
}
// Check that there is only one generic parameter, and store it as the singular option type.
List<? extends TypeMirror> genericParameters = optionDeclaredType.getTypeArguments();
if (genericParameters.size() != 1) {
throw new OptionProcessorException(
optionField,
"Option that allows multiple occurrences must be of type %s, "
+ "where E is the type of an individual command-line mention of this option, "
+ "but is of type %s",
listType,
optionType);
}
// For repeated options, we also accept cases where each option itself contains a list, which
// are then concatenated into the final single list type. For this reason, we will accept both
// converters that return the type of a single option, and List<singleOption>, which,
// incidentally, is the original optionType.
// Example: --foo=a,b,c --foo=d,e,f could have a final value of type List<Char>,
// value {a,b,c,e,d,f}, instead of requiring a final value of type List<List<Char>>
// value {{a,b,c},{d,e,f}}
TypeMirror singularOptionType = genericParameters.get(0);
return ImmutableList.of(singularOptionType, optionType);
} else {
return ImmutableList.of(optionField.asType());
}
}
static
private void createReportingMethod(JDefinedClass clazz, ExecutableElement executableElement, String operation, String initialOperation, JPrimitiveType type){
JCodeModel codeModel = clazz.owner();
String name = String.valueOf(executableElement.getSimpleName());
JMethod method = clazz.method(JMod.PUBLIC, clazz, name);
method.annotate(Override.class);
List<JVar> params = new ArrayList<>();
List<? extends VariableElement> parameterElements = executableElement.getParameters();
for(VariableElement parameterElement : parameterElements){
TypeMirror paramType = parameterElement.asType();
Name paramName = parameterElement.getSimpleName();
JVar param;
if((TypeKind.ARRAY).equals(paramType.getKind())){
ArrayType arrayType = (ArrayType)paramType;
param = method.varParam(toType(codeModel, arrayType.getComponentType()), String.valueOf(paramName));
} else
{
param = method.param(toType(codeModel, paramType), String.valueOf(paramName));
}
params.add(param);
}
String valueMethod;
if((codeModel.DOUBLE).equals(type)){
valueMethod = "doubleValue";
} else
if((codeModel.FLOAT).equals(type)){
valueMethod = "floatValue";
} else
{
throw new IllegalArgumentException();
}
boolean checkChange;
switch(name){
case "add":
case "subtract":
case "multiply":
case "divide":
checkChange = (clazz.name()).endsWith("Value");
break;
default:
checkChange = false;
break;
}
JBlock body = method.body();
JVar oldValueVar = null;
if(checkChange){
oldValueVar = body.decl(type, "oldValue", JExpr.invoke(valueMethod));
}
JVar resultVariable = body.decl(clazz, "result", JExpr.cast(clazz, createSuperInvocation(clazz, method)));
JVar newValueVar = null;
if(checkChange){
newValueVar = body.decl(type, "newValue", JExpr.invoke(valueMethod));
}
JBlock block = body;
if(checkChange){
block = body._if((oldValueVar).ne(newValueVar))._then();
}
if(initialOperation != null){
JConditional ifStatement = block._if(JExpr.invoke("hasExpression"));
JBlock trueBlock = ifStatement._then();
trueBlock.add(JExpr.invoke("report").arg(createReportInvocation(clazz, operation, params, type)));
JBlock falseBlock = ifStatement._else();
falseBlock.add(JExpr.invoke("report").arg(createReportInvocation(clazz, initialOperation, params, type)));
} else
{
block.add(JExpr.invoke("report").arg(createReportInvocation(clazz, operation, params, type)));
}
body._return(resultVariable);
}
/**
* Creates a reference from the parameter type
* and annotations on the parameter.
*/
public Reference(VariableElement param) {
this(param.asType(), param);
}