Java Code Examples for javax.lang.model.element.VariableElement#getEnclosingElement()

The following examples show how to use javax.lang.model.element.VariableElement#getEnclosingElement() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: WebBeansModelProviderImpl.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Override
public boolean isInjectionPoint( VariableElement element )  
    throws org.netbeans.modules.web.beans.api.model.InjectionPointDefinitionError
{
    Element parent = element.getEnclosingElement();
    
    if ( parent instanceof TypeElement){
        List<? extends AnnotationMirror> annotations = 
            getModel().getHelper().getCompilationController().getElements().
            getAllAnnotationMirrors(element);
        return getModel().getHelper().hasAnnotation(annotations, INJECT_ANNOTATION);
    }
    else if ( parent instanceof ExecutableElement ){
        return isMethodParameterInjection(element,(ExecutableElement)parent);
    }
    return false;
}
 
Example 2
Source File: MemberInjectorProcessor.java    From toothpick with Apache License 2.0 6 votes vote down vote up
private void processInjectAnnotatedField(
    VariableElement fieldElement,
    Map<TypeElement, List<FieldInjectionTarget>> mapTypeElementToMemberInjectorTargetList) {
  TypeElement enclosingElement = (TypeElement) fieldElement.getEnclosingElement();

  // Verify common generated code restrictions.
  if (!isValidInjectAnnotatedFieldOrParameter(fieldElement)) {
    return;
  }

  List<FieldInjectionTarget> fieldInjectionTargetList =
      mapTypeElementToMemberInjectorTargetList.get(enclosingElement);
  if (fieldInjectionTargetList == null) {
    fieldInjectionTargetList = new ArrayList<>();
    mapTypeElementToMemberInjectorTargetList.put(enclosingElement, fieldInjectionTargetList);
  }

  mapTypeToMostDirectSuperTypeThatNeedsInjection(enclosingElement);
  fieldInjectionTargetList.add(createFieldOrParamInjectionTarget(fieldElement));
}
 
Example 3
Source File: BriefnessProcessor.java    From Briefness with Apache License 2.0 6 votes vote down vote up
@Override
protected void processView(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
    Set<? extends Element> elementsWithBind = roundEnv.getElementsAnnotatedWith(BindView.class);
    for (Element element : elementsWithBind) {
        if (!checkAnnotationValid(element, BindView.class)) continue;
        VariableElement variableElement = (VariableElement) element;
        TypeElement classElement = (TypeElement) variableElement.getEnclosingElement();
        String fullClassName = classElement.getQualifiedName().toString();
        Briefnessor briefnessor = mProxyMap.get(fullClassName);
        if (briefnessor == null) {
            briefnessor = new Briefnessor(elementUtils, classElement);
            mProxyMap.put(fullClassName, briefnessor);
        }

    }
}
 
Example 4
Source File: InjectPresenterProcessor.java    From Moxy with MIT License 6 votes vote down vote up
@Override
public TargetClassInfo process(VariableElement variableElement) {
	final Element enclosingElement = variableElement.getEnclosingElement();

	if (!(enclosingElement instanceof TypeElement)) {
		throw new RuntimeException("Only class fields could be annotated as @InjectPresenter: " +
				variableElement + " at " + enclosingElement);
	}

	if (presentersContainers.contains(enclosingElement)) {
		return null;
	}

	final TypeElement presentersContainer = (TypeElement) enclosingElement;
	presentersContainers.add(presentersContainer);

	// gather presenter fields info
	List<TargetPresenterField> fields = collectFields(presentersContainer);
	bindProvidersToFields(fields, collectPresenterProviders(presentersContainer));
	bindTagProvidersToFields(fields, collectTagProviders(presentersContainer));

	return new TargetClassInfo(presentersContainer, fields);
}
 
Example 5
Source File: NavigationModelFieldUtil.java    From dart with Apache License 2.0 6 votes vote down vote up
private boolean isValidUsageOfNavigationModelField(VariableElement element) {
  final TypeElement enclosingElement = (TypeElement) element.getEnclosingElement();
  boolean valid = true;

  // Verify modifiers.
  Set<Modifier> modifiers = element.getModifiers();
  if (modifiers.contains(PRIVATE) || modifiers.contains(STATIC)) {
    loggingUtil.error(
        element,
        "@DartModel field must not be private or static. (%s.%s)",
        enclosingElement.getQualifiedName(),
        element.getSimpleName());
    valid = false;
  }

  return valid;
}
 
Example 6
Source File: MixinInfo.java    From picocli with Apache License 2.0 6 votes vote down vote up
public MixinInfo(VariableElement element, CommandSpec mixin) {
    this.element = element;
    this.mixin = mixin;

    String name = element.getAnnotation(CommandLine.Mixin.class).name();
    if (name.length() == 0) {
        name = element.getSimpleName().toString();
    }
    this.mixinName = name;
    Element targetType = element.getEnclosingElement();
    int position = -1;
    if (EnumSet.of(ElementKind.METHOD, ElementKind.CONSTRUCTOR).contains(targetType.getKind())) {
        List<? extends VariableElement> parameters = ((ExecutableElement) targetType).getParameters();
        for (int i = 0; i < parameters.size(); i++) {
            if (parameters.get(i).getSimpleName().contentEquals(element.getSimpleName())) {
                position = i;
                break;
            }
        }
    }
    annotatedElement = new TypedMember(element, position);
}
 
Example 7
Source File: GoToSupport.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public Void visitVariable(VariableElement e, Boolean highlightName) {
    modifier(e.getModifiers());
    
    result.append(getTypeName(info, e.asType(), true));
    
    result.append(' ');
    
    boldStartCheck(highlightName);

    result.append(e.getSimpleName());
    
    boldStopCheck(highlightName);
    
    if (highlightName) {
        if (e.getConstantValue() != null) {
            result.append(" = ");
            result.append(StringEscapeUtils.escapeHtml(e.getConstantValue().toString()));
        }
        
        Element enclosing = e.getEnclosingElement();
        
        if (e.getKind() != ElementKind.PARAMETER && e.getKind() != ElementKind.LOCAL_VARIABLE
                && e.getKind() != ElementKind.RESOURCE_VARIABLE && e.getKind() != ElementKind.EXCEPTION_PARAMETER
                && !TreeShims.BINDING_VARIABLE.equals(e.getKind().name())) {
            result.append(" in ");

            //short typename:
            result.append(getTypeName(info, enclosing.asType(), true));
        }
    }
    
    return null;
}
 
Example 8
Source File: JavaSourceParserUtil.java    From jeddict with Apache License 2.0 5 votes vote down vote up
/**
 * guess getter from var
 *
 * @param variableElement
 * @return
 */
public static ExecutableElement guessGetter(VariableElement variableElement) {
    String name = variableElement.getSimpleName().toString();
    String guessGetterName = StringHelper.firstUpper(name);
    TypeElement typeElement = (TypeElement) variableElement.getEnclosingElement();
    for (ExecutableElement executableElement : ElementFilter.methodsIn(typeElement.getEnclosedElements())) {
        if (executableElement.getSimpleName().contentEquals("get" + guessGetterName) || executableElement.getSimpleName().contentEquals("is" + guessGetterName)) {
            return executableElement;
        }
    }
    Logger.getLogger(JavaSourceParserUtil.class.getName()).log(Level.INFO, "Cannot detect getter associated with var: {0}", guessGetterName);
    return null;
}
 
Example 9
Source File: DelegateFieldAnalizer.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public void analyze( VariableElement element, TypeMirror elementType,
        TypeElement parent, AtomicBoolean cancel,
        CdiAnalysisResult result )
{
    CompilationInfo compInfo = result.getInfo();
    if (!AnnotationUtil.hasAnnotation(element, AnnotationUtil.DELEGATE_FQN, 
            compInfo))
    {
        return;
    }
    result.requireCdiEnabled(element);
    if (!AnnotationUtil.hasAnnotation(element, AnnotationUtil.INJECT_FQN,
            compInfo))
    {
        result.addError(element,  NbBundle.getMessage(
                        DelegateFieldAnalizer.class,
                        "ERR_DelegateHasNoInject"));        // NOI18N
    }
    Element clazz = element.getEnclosingElement();
    if (!AnnotationUtil.hasAnnotation(clazz, AnnotationUtil.DECORATOR,
            compInfo))
    {
        result.addError(element,  NbBundle.getMessage(
                        DelegateFieldAnalizer.class,
                        "ERR_DelegateIsNotInDecorator"));   // NOI18N
    }
    EditorAnnotationsHelper helper = EditorAnnotationsHelper.getInstance(
            result);
    if ( helper != null ){
        helper.addDelegate(result, element );
    }
    if ( cancel.get()){
        return;
    }
    checkDelegateType(element, elementType, parent, result );
}
 
Example 10
Source File: WebBeansModelProviderImpl.java    From netbeans with Apache License 2.0 5 votes vote down vote up
protected DependencyInjectionResult lookupInjectables( VariableElement element,
        DeclaredType parentType , ResultLookupStrategy strategy, AtomicBoolean cancel)
{
    /* 
     * Element could be injection point. One need first if all to check this.  
     */
    Element parent = element.getEnclosingElement();
    
    if(cancel.get()) {
        return null;
    }
    
    if ( parent instanceof TypeElement){
        return findVariableInjectable(element, parentType , strategy, cancel);
    }
    else if ( parent instanceof ExecutableElement ){
        // Probably injected field in method. One need to check method.
        /*
         * There are two cases where parameter is injected :
         * 1) Method has some annotation which require from 
         * parameters to be injection points.
         * 2) Method is disposer method. In this case injectable
         * is producer corresponding method.
         */
        return findParameterInjectable(element, parentType, strategy, cancel);
    }
    
    return null;
}
 
Example 11
Source File: ToothpickProcessor.java    From toothpick with Apache License 2.0 5 votes vote down vote up
protected boolean isValidInjectAnnotatedFieldOrParameter(VariableElement variableElement) {
  TypeElement enclosingElement = (TypeElement) variableElement.getEnclosingElement();

  // Verify modifiers.
  Set<Modifier> modifiers = variableElement.getModifiers();
  if (modifiers.contains(PRIVATE)) {
    error(
        variableElement,
        "@Inject annotated fields must be non private : %s#%s",
        enclosingElement.getQualifiedName(),
        variableElement.getSimpleName());
    return false;
  }

  // Verify parentScope modifiers.
  Set<Modifier> parentModifiers = enclosingElement.getModifiers();
  if (parentModifiers.contains(PRIVATE)) {
    error(
        variableElement,
        "@Injected fields in class %s. The class must be non private.",
        enclosingElement.getSimpleName());
    return false;
  }

  if (!isValidInjectedType(variableElement)) {
    return false;
  }
  return true;
}
 
Example 12
Source File: MethodParameterElement.java    From revapi with Apache License 2.0 5 votes vote down vote up
public MethodParameterElement(ProbingEnvironment env, Archive archive, VariableElement element, TypeMirror type) {
    super(env, archive, element, type);
    if (element.getEnclosingElement() instanceof ExecutableElement) {
        index = ((ExecutableElement) element.getEnclosingElement()).getParameters().indexOf(element);
    } else {
        throw new IllegalArgumentException(
            "MethodParameterElement cannot be constructed using a VariableElement not representing a method parameter.");
    }
}
 
Example 13
Source File: RenamePanel.java    From netbeans with Apache License 2.0 4 votes vote down vote up
@Override
  public void initialize() {
      if (initialized) {
          return;
      }

      if (handle!=null && handle.getKind() != Tree.Kind.LABELED_STATEMENT &&
              handle.getElementHandle() != null 
              && (handle.getElementHandle().getKind() == ElementKind.FIELD
              || handle.getElementHandle().getKind() == ElementKind.CLASS
|| handle.getElementHandle().getKind() == ElementKind.METHOD)) {
          JavaSource source = JavaSource.forFileObject(handle.getFileObject());
          CancellableTask<CompilationController> task = new CancellableTask<CompilationController>() {

              @Override
              public void cancel() {
                  throw new UnsupportedOperationException("Not supported yet."); // NOI18N
              }

              @Override
              public void run(CompilationController info) throws Exception {
                  info.toPhase(Phase.RESOLVED);
                  if(handle.getElementHandle().getKind() == ElementKind.FIELD) {
                      VariableElement element = (VariableElement) handle.resolveElement(info);
                      if(element == null) {
                          LOG.log(Level.WARNING, "Cannot resolve ElementHandle {0} {1}", new Object[] {handle, info.getClasspathInfo()});
                          return;
                      }
                      TypeElement parent = (TypeElement) element.getEnclosingElement();
                      boolean hasGetters = false;
                      for (ExecutableElement method : ElementFilter.methodsIn(parent.getEnclosedElements())) {
                          if (RefactoringUtils.isGetter(info, method, element) || RefactoringUtils.isSetter(info, method, element)) {
                              hasGetters = true;
                              break;
                          }
                      }

                      if (hasGetters) {
                          SwingUtilities.invokeLater(new Runnable() {

                              @Override
                              public void run() {
                                  renameGettersAndCheckersCheckBox.setVisible(true);
                              }
                          });
                      }
                  }
                  
                  if(handle.getElementHandle().getKind() == ElementKind.CLASS || handle.getElementHandle().getKind() == ElementKind.METHOD) {
	final Element methodElement = handle.resolveElement(info);
                      if(methodElement == null) {
                          LOG.log(Level.WARNING, "Cannot resolve ElementHandle {0} {1}", new Object[] {handle, info.getClasspathInfo()});
                          return;
                      }
                      final FileObject fileObject = handle.getFileObject();
                      Collection<? extends TestLocator> testLocators = Lookup.getDefault().lookupAll(TestLocator.class);
                      for (final TestLocator testLocator : testLocators) {
                          if(testLocator.appliesTo(fileObject)) {
                              if(testLocator.asynchronous()) {
                                  testLocator.findOpposite(fileObject, -1, new TestLocator.LocationListener() {

                                      @Override
                                      public void foundLocation(FileObject fo, LocationResult location) {
			    if(handle.getElementHandle().getKind() == ElementKind.CLASS) {
				addTestFile(location, testLocator);
			    } else if(handle.getElementHandle().getKind() == ElementKind.METHOD) {
				addTestMethod(location, testLocator, methodElement);
			    }
                                      }
                                  });
                              } else {
		    if(handle.getElementHandle().getKind() == ElementKind.CLASS) {
			addTestFile(testLocator.findOpposite(fileObject, -1), testLocator);
		    } else if (handle.getElementHandle().getKind() == ElementKind.METHOD) {
			addTestMethod(testLocator.findOpposite(fileObject, -1), testLocator, methodElement);
		    }
                              }
                          }
                      }
                  }
              }
          };
          try {
              source.runUserActionTask(task, true);
          } catch (IOException ioe) {
              throw new RuntimeException(ioe);
          }
      }
      
      initialized = true;
  }
 
Example 14
Source File: ExtraAnnotatedClass.java    From PrettyBundle with Apache License 2.0 4 votes vote down vote up
public ExtraAnnotatedClass(VariableElement annotatedVariableElement, Elements elements, Types types) {
    this.annotatedVariableElement = annotatedVariableElement;
    key = annotatedVariableElement.getSimpleName().toString();
    // Get the full QualifiedTypeName
    final TypeElement parent = (TypeElement) annotatedVariableElement.getEnclosingElement();
    if (types.isSubtype(parent.asType(), elements.getTypeElement("android.app.Activity").asType())) {
        supportedType = SupportedType.ACTIVITY;
    } else if (types.isSubtype(parent.asType(), elements.getTypeElement("android.app.Service").asType())) {
        supportedType = SupportedType.SERVICE;
    } else if (types.isSubtype(parent.asType(), elements.getTypeElement("android.app.Fragment").asType())
            || types.isSubtype(parent.asType(), elements.getTypeElement("android.support.v4.app.Fragment").asType())) {
        supportedType = SupportedType.FRAGMENT;
    } else {
        supportedType = SupportedType.NOP;
    }
    qualifiedClassName = parent.getQualifiedName().toString();
    // Get the full Qualified of DataType.
    dataType = annotatedVariableElement.asType();
    dataTypeQualifiedClassName = dataType.toString();
    extraBinder = ExtraBinderProvider.get(dataTypeQualifiedClassName);
    if (extraBinder != ExtraBinder.NOP) {
        return;
    }
    // Check if data type is kind of Parcelable.
    if (types.isSubtype(dataType, elements.getTypeElement("android.os.Parcelable").asType())) {
        extraBinder = ExtraBinderProvider.get("android.os.Parcelable");
        if (extraBinder != ExtraBinder.NOP) {
            return;
        }
    }

    try {
        // Check if data type is kind of Array.
        dataTypeQualifiedClassName = ((ArrayType) dataType).getComponentType().toString();
        final TypeMirror componentTypeMirror = elements.getTypeElement(dataTypeQualifiedClassName).asType();
        if (types.isSubtype(componentTypeMirror, elements.getTypeElement("android.os.Parcelable").asType())) {
            extraBinder = ExtraBinderProvider.get("android.os.Parcelable[]");
            if (extraBinder != ExtraBinder.NOP) {
                return;
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example 15
Source File: ApNavigator.java    From TencentKona-8 with GNU General Public License v2.0 4 votes vote down vote up
public TypeElement getDeclaringClassForField(VariableElement f) {
    return (TypeElement) f.getEnclosingElement();
}
 
Example 16
Source File: ApNavigator.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 4 votes vote down vote up
public TypeElement getDeclaringClassForField(VariableElement f) {
    return (TypeElement) f.getEnclosingElement();
}
 
Example 17
Source File: ApNavigator.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
public TypeElement getDeclaringClassForField(VariableElement f) {
    return (TypeElement) f.getEnclosingElement();
}
 
Example 18
Source File: ApNavigator.java    From openjdk-jdk8u with GNU General Public License v2.0 4 votes vote down vote up
public TypeElement getDeclaringClassForField(VariableElement f) {
    return (TypeElement) f.getEnclosingElement();
}
 
Example 19
Source File: ApNavigator.java    From openjdk-8 with GNU General Public License v2.0 4 votes vote down vote up
public TypeElement getDeclaringClassForField(VariableElement f) {
    return (TypeElement) f.getEnclosingElement();
}
 
Example 20
Source File: ApNavigator.java    From openjdk-8-source with GNU General Public License v2.0 4 votes vote down vote up
public TypeElement getDeclaringClassForField(VariableElement f) {
    return (TypeElement) f.getEnclosingElement();
}