Java Code Examples for javax.lang.model.element.Modifier

The following examples show how to use javax.lang.model.element.Modifier. 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 check out the related API usage on the sidebar.
Example #1
Source Project: firebase-android-sdk   Author: firebase   File: HashCodeMethod.java    License: Apache License 2.0 6 votes vote down vote up
static MethodSpec generate(TypeElement annotation) {
  MethodSpec.Builder hashCodeBuilder =
      MethodSpec.methodBuilder("hashCode")
          .addModifiers(Modifier.PUBLIC)
          .addAnnotation(Override.class)
          .returns(int.class);

  List<ExecutableElement> methods = ElementFilter.methodsIn(annotation.getEnclosedElements());
  if (methods.isEmpty()) {
    hashCodeBuilder.addCode("return 0;\n");
    return hashCodeBuilder.build();
  }

  CodeBlock.Builder code = CodeBlock.builder().add("return ");
  for (ExecutableElement method : methods) {
    code.add(
        "+ ($L ^ $L)\n",
        127 * method.getSimpleName().toString().hashCode(),
        hashExpression(method));
  }
  code.add(";\n");
  hashCodeBuilder.addCode(code.build());

  return hashCodeBuilder.build();
}
 
Example #2
Source Project: squidb   Author: yahoo   File: ModelMethodPlugin.java    License: Apache License 2.0 6 votes vote down vote up
private void emitModelMethod(JavaFileWriter writer, ExecutableElement e, Modifier... modifiers)
        throws IOException {
    MethodDeclarationParameters params = utils.methodDeclarationParamsFromExecutableElement(e, modifiers);

    ModelMethod methodAnnotation = e.getAnnotation(ModelMethod.class);
    List<Object> arguments = new ArrayList<>();
    if (methodAnnotation != null) {
        String name = methodAnnotation.name();
        if (!AptUtils.isEmpty(name)) {
            params.setMethodName(name);
        }
        params.getArgumentTypes().remove(0);
        params.getArgumentNames().remove(0);
        arguments.add(0, "this");
    }
    arguments.addAll(params.getArgumentNames());
    Expression methodCall = Expressions.staticMethod(modelSpec.getModelSpecName(),
            e.getSimpleName().toString(), arguments);
    if (!CoreTypes.VOID.equals(params.getReturnType())) {
        methodCall = methodCall.returnExpr();
    }
    JavadocPlugin.writeJavadocFromElement(pluginEnv, writer, e);
    writer.beginMethodDefinition(params)
            .writeStatement(methodCall)
            .finishMethodDefinition();
}
 
Example #3
Source Project: javapoet   Author: square   File: TypeSpecTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test public void classImplementsNestedClass() throws Exception {
  ClassName outer = ClassName.get(tacosPackage, "Outer");
  ClassName inner = outer.nestedClass("Inner");
  ClassName callable = ClassName.get(Callable.class);
  TypeSpec typeSpec = TypeSpec.classBuilder("Outer")
      .superclass(ParameterizedTypeName.get(callable,
          inner))
      .addType(TypeSpec.classBuilder("Inner")
          .addModifiers(Modifier.STATIC)
          .build())
      .build();

  assertThat(toString(typeSpec)).isEqualTo(""
      + "package com.squareup.tacos;\n"
      + "\n"
      + "import java.util.concurrent.Callable;\n"
      + "\n"
      + "class Outer extends Callable<Outer.Inner> {\n"
      + "  static class Inner {\n"
      + "  }\n"
      + "}\n");
}
 
Example #4
Source Project: fragmentargs   Author: sockeqwe   File: ArgProcessor.java    License: Apache License 2.0 6 votes vote down vote up
private void writeNewFragmentWithRequiredMethod(String builder, TypeElement element,
                                                JavaWriter jw, String[] args) throws IOException {

    if (supportAnnotations) jw.emitAnnotation("NonNull");
    jw.beginMethod(element.getQualifiedName().toString(), "new" + element.getSimpleName(),
            EnumSet.of(Modifier.STATIC, Modifier.PUBLIC), args);
    StringBuilder argNames = new StringBuilder();
    for (int i = 1; i < args.length; i += 2) {
        argNames.append(args[i]);
        if (i < args.length - 1) {
            argNames.append(", ");
        }
    }
    jw.emitStatement("return new %1$s(%2$s).build()", builder, argNames);
    jw.endMethod();
}
 
Example #5
Source Project: netbeans   Author: apache   File: ClipboardHandler.java    License: Apache License 2.0 6 votes vote down vote up
private static Element fqn2element(final Elements elements, final String fqn) {
    if (fqn == null) {
        return null;
    }
    TypeElement type = elements.getTypeElement(fqn);
    if (type != null) {
        return type;
    }
    int idx = fqn.lastIndexOf('.');
    if (idx > 0) {
        type = elements.getTypeElement(fqn.substring(0, idx));
        String name = fqn.substring(idx + 1);
        if (type != null && name.length() > 0) {
            for (Element el : type.getEnclosedElements()) {
                if (el.getModifiers().contains(Modifier.STATIC) && name.contentEquals(el.getSimpleName())) {
                    return el;
                }
            }
        }
    }
    return null;
}
 
Example #6
Source Project: caffeine   Author: ben-manes   File: NodeFactoryGenerator.java    License: Apache License 2.0 6 votes vote down vote up
private void addNewFactoryMethods() {
  nodeFactory.addMethod(MethodSpec.methodBuilder("newFactory")
      .addJavadoc("Returns a factory optimized for the specified features.\n")
      .addModifiers(Modifier.PUBLIC, Modifier.STATIC)
      .addTypeVariable(kTypeVar)
      .addTypeVariable(vTypeVar)
      .addParameter(BUILDER_PARAM)
      .addParameter(boolean.class, "isAsync")
      .addCode(NodeSelectorCode.get())
      .returns(NODE_FACTORY)
      .build());
  nodeFactory.addMethod(MethodSpec.methodBuilder("weakValues")
      .addJavadoc("Returns whether this factory supports weak values.\n")
      .addModifiers(Modifier.PUBLIC, Modifier.DEFAULT)
      .addStatement("return false")
      .returns(boolean.class)
      .build());
  nodeFactory.addMethod(MethodSpec.methodBuilder("softValues")
      .addJavadoc("Returns whether this factory supports soft values.\n")
      .addModifiers(Modifier.PUBLIC, Modifier.DEFAULT)
      .addStatement("return false")
      .returns(boolean.class)
      .build());
}
 
Example #7
Source Project: netbeans   Author: apache   File: GenerationUtilsTest.java    License: Apache License 2.0 6 votes vote down vote up
public void testCreateProperty() throws Exception {
    TestUtilities.copyStringToFileObject(testFO,
            "package foo;" +
            "public class TestClass {" +
            "   private Object x;" +
            "   public TestClass() {" +
            "   }" +
            "}");
    runModificationTask(testFO, new Task<WorkingCopy>() {
        public void run(WorkingCopy copy) throws Exception {
            GenerationUtils genUtils = GenerationUtils.newInstance(copy);
            ClassTree classTree = (ClassTree)copy.getCompilationUnit().getTypeDecls().get(0);
            TypeElement scope = SourceUtils.classTree2TypeElement(copy, classTree);
            VariableTree field = genUtils.createField(scope, genUtils.createModifiers(Modifier.PRIVATE), "someProp", "java.lang.String", null);
            MethodTree getter = genUtils.createPropertyGetterMethod(scope, genUtils.createModifiers(Modifier.PUBLIC), "someProp", "java.lang.String");
            MethodTree setter = genUtils.createPropertySetterMethod(scope, genUtils.createModifiers(Modifier.PUBLIC), "someProp", "java.lang.String");
            TreeMaker make = copy.getTreeMaker();
            ClassTree newClassTree = classTree;
            newClassTree = make.insertClassMember(newClassTree, 0, field);
            newClassTree = make.addClassMember(newClassTree, getter);
            newClassTree = make.addClassMember(newClassTree, setter);
            copy.rewrite(classTree, newClassTree);
        }
    }).commit();
    // TODO check the field and methods
}
 
Example #8
Source Project: ActivityRouter   Author: mzule   File: RouterProcessor.java    License: Apache License 2.0 6 votes vote down vote up
private void generateModulesRouterInit(String[] moduleNames) {
    MethodSpec.Builder initMethod = MethodSpec.methodBuilder("init")
            .addModifiers(Modifier.PUBLIC, Modifier.FINAL, Modifier.STATIC);
    for (String module : moduleNames) {
        initMethod.addStatement("RouterMapping_" + module + ".map()");
    }
    TypeSpec routerInit = TypeSpec.classBuilder("RouterInit")
            .addModifiers(Modifier.PUBLIC, Modifier.FINAL)
            .addMethod(initMethod.build())
            .build();
    try {
        JavaFile.builder("com.github.mzule.activityrouter.router", routerInit)
                .build()
                .writeTo(filer);
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example #9
Source Project: Akatsuki   Author: tom91136   File: RetainedStateIntegrationTestBase.java    License: Apache License 2.0 6 votes vote down vote up
protected void testGenericType(String parameterName, Class<?>... input) {
	// we could make Field support <T> but that's too much effort for this
	// single use case

	String fieldName = parameterName.toLowerCase(Locale.ENGLISH);
	final TypeVariableName typeVariable = TypeVariableName.get(parameterName, input);
	FieldSpec field = field(TypeVariableName.get(parameterName), fieldName, Retained.class);
	final TestSource source = new TestSource(TEST_PACKAGE, generateClassName(), Modifier.PUBLIC)
			.appendFields(field)
			.appendTransformation((b, s) -> b.addTypeVariable(typeVariable));
	final RetainedStateTestEnvironment environment = new RetainedStateTestEnvironment(this,
			source);
	environment.tester().invokeSaveAndRestore();
	environment.tester().testSaveRestoreInvocation(name -> true, BundleRetainerTester.CLASS_EQ,
			Collections.singletonList(new RetainedTestField(input[0], fieldName)), f -> 1);

}
 
Example #10
Source Project: AirData   Author: baoyongzhang   File: DAOCreator.java    License: MIT License 6 votes vote down vote up
private MethodSpec generatorQueryMethod() {
    MethodSpec.Builder queryBuilder = MethodSpec.methodBuilder("query")
            .addModifiers(Modifier.PUBLIC)
            .returns(ClassName.get(List.class))
            .addParameter(TypeName.BOOLEAN, "distinct")
            .addParameter(ArrayTypeName.of(ClassName.get(String.class)), "columns")
            .addParameter(ClassName.get(String.class), "selection")
            .addParameter(ArrayTypeName.of(ClassName.get(String.class)), "selectionArgs")
            .addParameter(ClassName.get(String.class), "groupBy")
            .addParameter(ClassName.get(String.class), "having")
            .addParameter(ClassName.get(String.class), "orderBy")
            .addParameter(ClassName.get(String.class), "limit")
            .addStatement("$T cursor = this.rawQuery(distinct, columns, selection, selectionArgs, groupBy, having, orderBy, limit)", ClassName.get("android.database", "Cursor"));
    queryBuilder.addStatement("$T list = new $T()", ArrayList.class, ArrayList.class);
    queryBuilder.addCode("if (cursor.moveToFirst()) {");
    queryBuilder.addCode("  do {");
    queryBuilder.addCode("     list.add(fillData(cursor));");
    queryBuilder.addCode("  } while (cursor.moveToNext());");
    queryBuilder.addCode("}");
    queryBuilder.addStatement("return list");
    return queryBuilder.build();
}
 
Example #11
Source Project: netbeans   Author: apache   File: ClassStructure.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected void performRewrite(TransformationContext ctx) {
    WorkingCopy wc = ctx.getWorkingCopy();
    GeneratorUtilities gu = GeneratorUtilities.get(wc);
    TreePath path = ctx.getPath();
    final ClassTree cls = (ClassTree) path.getLeaf();
    gu.importComments(cls, wc.getCompilationUnit());
    final TreeMaker treeMaker = wc.getTreeMaker();
    ModifiersTree mods = cls.getModifiers();
    if (mods.getFlags().contains(Modifier.ABSTRACT)) {
        Set<Modifier> modifiers = EnumSet.copyOf(mods.getFlags());
        modifiers.remove(Modifier.ABSTRACT);
        ModifiersTree nmods = treeMaker.Modifiers(modifiers, mods.getAnnotations());
        gu.copyComments(mods, nmods, true);
        gu.copyComments(mods, nmods, false);
        mods = nmods;
    }
    Tree nue = treeMaker.Interface(mods, cls.getSimpleName(), cls.getTypeParameters(), cls.getImplementsClause(), cls.getMembers());
    gu.copyComments(cls, nue, true);
    gu.copyComments(cls, nue, false);
    wc.rewrite(path.getLeaf(), nue);
}
 
Example #12
Source Project: javapoet   Author: square   File: TypeSpecTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test public void innerAnnotationInAnnotationDeclaration() throws Exception {
  TypeSpec bar = TypeSpec.annotationBuilder("Bar")
      .addMethod(MethodSpec.methodBuilder("value")
          .addModifiers(Modifier.PUBLIC, Modifier.ABSTRACT)
          .defaultValue("@$T", Deprecated.class)
          .returns(Deprecated.class)
          .build())
      .build();

  assertThat(toString(bar)).isEqualTo(""
      + "package com.squareup.tacos;\n"
      + "\n"
      + "import java.lang.Deprecated;\n"
      + "\n"
      + "@interface Bar {\n"
      + "  Deprecated value() default @Deprecated;\n"
      + "}\n"
  );
}
 
Example #13
Source Project: netbeans   Author: apache   File: EntityGenerateFromIntfVisitor.java    License: Apache License 2.0 5 votes vote down vote up
public void visit(HomeMethodType hmt) {
    implMethod = hmt.getMethodElement();
    String origName = implMethod.getName();
    String newName = prependAndUpper(origName,"ejbHome"); //NOI18N
    String body = TODO + implMethod.getName() + implMethod.getReturnType();
    implMethod = MethodModel.create(
            newName, 
            implMethod.getReturnType(),
            body,
            implMethod.getParameters(),
            implMethod.getExceptions(),
            Collections.singleton(Modifier.PUBLIC)
            );
}
 
Example #14
Source Project: AndServer   Author: yanzhenjie   File: ControllerProcessor.java    License: Apache License 2.0 5 votes vote down vote up
private void findMapping(Set<? extends Element> set, Map<TypeElement, List<ExecutableElement>> controllerMap) {
    for (Element element : set) {
        if (element instanceof ExecutableElement) {
            ExecutableElement execute = (ExecutableElement) element;
            Element enclosing = element.getEnclosingElement();
            if (!(enclosing instanceof TypeElement)) {
                continue;
            }

            TypeElement type = (TypeElement) enclosing;
            Annotation restController = type.getAnnotation(RestController.class);
            Annotation controller = type.getAnnotation(Controller.class);
            if (restController == null && controller == null) {
                mLog.w(String.format("Controller/RestController annotations may be missing on %s.",
                    type.getQualifiedName()));
                continue;
            }

            String host = type.getQualifiedName() + "#" + execute.getSimpleName() + "()";

            Set<Modifier> modifiers = execute.getModifiers();
            Validate.isTrue(!modifiers.contains(Modifier.PRIVATE), "The modifier private is redundant on %s.",
                host);

            if (modifiers.contains(Modifier.STATIC)) {
                mLog.w(String.format("The modifier static is redundant on %s.", host));
            }

            List<ExecutableElement> elementList = controllerMap.get(type);
            if (CollectionUtils.isEmpty(elementList)) {
                elementList = new ArrayList<>();
                controllerMap.put(type, elementList);
            }
            elementList.add(execute);
        }
    }
}
 
Example #15
Source Project: tutorials   Author: eugenp   File: PersonGenerator.java    License: MIT License 5 votes vote down vote up
public TypeSpec getGenderEnum() {
    return TypeSpec
      .enumBuilder("Gender")
      .addModifiers(Modifier.PUBLIC)
      .addEnumConstant("MALE")
      .addEnumConstant("FEMALE")
      .addEnumConstant("UNSPECIFIED")
      .build();
}
 
Example #16
Source Project: netbeans   Author: apache   File: MissingHashCode.java    License: Apache License 2.0 5 votes vote down vote up
public void run(WorkingCopy wc) throws Exception {
    wc.toPhase(JavaSource.Phase.ELEMENTS_RESOLVED);
    for (Element elem : handle.resolveElement(wc).getEnclosedElements()) {
        if (elem.getKind() == ElementKind.FIELD) {
            if (!elem.getModifiers().contains(Modifier.STATIC)) {
                fieldFound = true;
                return;
            }
        }
    }
    EqualsHashCodeGenerator.generateEqualsAndHashCode(wc, handle.resolve(wc));
}
 
Example #17
Source Project: RapidORM   Author: wangjiegulu   File: TableEntry.java    License: Apache License 2.0 5 votes vote down vote up
public JavaFile brewJava() throws Throwable {
    parse();

    LogUtil.logger("mSourceClassEle: " + mSourceClassEle + ", mColumnList: " + mColumnList);

    String sourceClassSimpleName = mSourceClassEle.getSimpleName().toString();
    String targetClassSimpleName = sourceClassSimpleName + STUFF_RAPID_ORM_TABLE;
    String targetPackage = mSourceClassEle.getEnclosingElement().toString();

    TypeSpec.Builder result = TypeSpec.classBuilder(targetClassSimpleName)
            .addModifiers(Modifier.PUBLIC)
            .superclass( // extends TableConfig
                    ParameterizedTypeName.get(
                            ClassName.bestGuess(GuessClass.BASE_TABLE_CONFIG),
                            mSourceClassEleTypeName
                    )
            );

    // Constructor method
    MethodSpec.Builder constructorMethod = MethodSpec.constructorBuilder()
            .addModifiers(Modifier.PUBLIC)
            .addStatement("super($T.class)", mSourceClassEleTypeName);

    overrideParseAllConfigsMethod(result);

    implementModelPropertyMethods(result);

    result.addMethod(constructorMethod.build());

    return JavaFile.builder(targetPackage, result.build())
            .addFileComment("GENERATED CODE BY RapidORM. DO NOT MODIFY! $S, Source table: $S",
                    DATE_FORMAT.format(new Date(System.currentTimeMillis())),
                    mSourceClassEle.asType().toString())
            .skipJavaLangImports(true)
            .build();
}
 
Example #18
Source Project: aws-sdk-java-v2   Author: aws   File: ServiceMetadataGenerator.java    License: Apache License 2.0 5 votes vote down vote up
private MethodSpec regions() {
    TypeName listOfRegions = ParameterizedTypeName.get(ClassName.get(List.class),
                                                       ClassName.get(regionBasePackage, "Region"));
    return MethodSpec.methodBuilder("regions")
                     .addModifiers(Modifier.PUBLIC)
                     .addAnnotation(Override.class)
                     .returns(listOfRegions)
                     .addStatement("return $L", "REGIONS")
                     .build();
}
 
Example #19
Source Project: bazel   Author: bazelbuild   File: AutoCodecProcessor.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Adds fields to the codec class to hold offsets and adds a constructor to initialize them.
 *
 * <p>For a parameter with name {@code target}, the field will have name {@code target_offset}.
 *
 * @param parameters constructor parameters
 */
private void initializeUnsafeOffsets(
    TypeSpec.Builder builder,
    TypeElement encodedType,
    List<? extends VariableElement> parameters) {
  MethodSpec.Builder constructor = MethodSpec.constructorBuilder();
  for (VariableElement param : parameters) {
    Optional<FieldValueAndClass> field =
        getFieldByNameRecursive(encodedType, param.getSimpleName().toString());
    if (!field.isPresent()) {
      // Will attempt to use a getter for this field instead.
      continue;
    }
    builder.addField(
        TypeName.LONG, param.getSimpleName() + "_offset", Modifier.PRIVATE, Modifier.FINAL);
    constructor.beginControlFlow("try");
    constructor.addStatement(
        "this.$L_offset = $T.getInstance().objectFieldOffset($T.class.getDeclaredField(\"$L\"))",
        param.getSimpleName(),
        UnsafeProvider.class,
        ClassName.get(field.get().declaringClassType),
        param.getSimpleName());
    constructor.nextControlFlow("catch ($T e)", NoSuchFieldException.class);
    constructor.addStatement("throw new $T(e)", IllegalStateException.class);
    constructor.endControlFlow();
  }
  builder.addMethod(constructor.build());
}
 
Example #20
Source Project: RxAndroidOrm   Author: florent37   File: ProcessUtils.java    License: Apache License 2.0 5 votes vote down vote up
public static List<VariableElement> filterStaticFinal(List<VariableElement> elements) {
    List<VariableElement> filtered = new ArrayList<>();
    for (VariableElement variableElement : elements) {
        final Set<Modifier> modifiers = variableElement.getModifiers();
        if (!modifiers.containsAll(Arrays.asList(Modifier.FINAL, Modifier.STATIC))) {
            filtered.add(variableElement);
        }
    } return filtered;
}
 
Example #21
Source Project: caffeine   Author: ben-manes   File: LocalCacheFactoryGenerator.java    License: Apache License 2.0 5 votes vote down vote up
void generate() throws IOException {
  factory = TypeSpec.classBuilder("LocalCacheFactory")
      .addModifiers(Modifier.FINAL)
      .addMethod(MethodSpec.constructorBuilder().addModifiers(Modifier.PRIVATE).build());
  addClassJavaDoc();
  addConstants();

  generateLocalCaches();
  addFactoryMethods();
  writeJavaFile();
}
 
Example #22
Source Project: j2objc   Author: google   File: PackageInfoRewriter.java    License: Apache License 2.0 5 votes vote down vote up
private MethodDeclaration createPrefixMethod(String prefix, TypeElement type) {
  ExecutableElement element = GeneratedExecutableElement.newMethodWithSelector(
      "__prefix", typeUtil.getJavaString().asType(), type)
      .addModifiers(Modifier.STATIC);
  MethodDeclaration method = new MethodDeclaration(element);
  method.setHasDeclaration(false);
  Block body = new Block();
  method.setBody(body);
  body.addStatement(new ReturnStatement(new StringLiteral(prefix, typeUtil)));
  return method;
}
 
Example #23
Source Project: android-sqlite-generator   Author: Trikke   File: ContentProviderWriter.java    License: Apache License 2.0 5 votes vote down vote up
private void emitFields() throws IOException
{
	writer.emitEmptyLine();
	writer.emitField( "String", "TAG", EnumSet.of( Modifier.PRIVATE, Modifier.STATIC, Modifier.FINAL ), "\"" + mModel.getContentProviderName() + "\"" );
	writer.emitField( "String", "DATABASE_NAME", EnumSet.of( Modifier.PRIVATE, Modifier.STATIC, Modifier.FINAL ), "\"" + mModel.getDbClassName() + ".db\"" );
	writer.emitField( "int", "DATABASE_VERSION", EnumSet.of( Modifier.PRIVATE, Modifier.STATIC, Modifier.FINAL ), String.valueOf( mModel.getDbVersion() ) );
	writer.emitField( "String", "ROW_ID", EnumSet.of( Modifier.PRIVATE, Modifier.STATIC, Modifier.FINAL ), "\"" + Table.ANDROID_ID + "\"" );
	writer.emitEmptyLine();
	writer.emitField( "String", "AUTHORITY", EnumSet.of( Modifier.PUBLIC, Modifier.STATIC, Modifier.FINAL ), "\"" + mModel.getContentAuthority() + "\"" );
	writer.emitEmptyLine();
	writer.emitField( mModel.getDbClassName(), "mLocalDatabase", EnumSet.of( Modifier.PRIVATE ) );
	writer.emitEmptyLine();
}
 
Example #24
Source Project: j2objc   Author: google   File: ArrayRewriter.java    License: Apache License 2.0 5 votes vote down vote up
private MethodInvocation newInitializedArrayInvocation(
    ArrayType arrayType, List<Expression> elements, boolean retainedResult) {
  TypeMirror componentType = arrayType.getComponentType();
  TypeElement iosArrayElement = typeUtil.getIosArray(componentType);

  GeneratedExecutableElement methodElement = GeneratedExecutableElement.newMethodWithSelector(
      getInitializeSelector(componentType, retainedResult), iosArrayElement.asType(),
      iosArrayElement)
      .addModifiers(Modifier.PUBLIC, Modifier.STATIC);
  methodElement.addParameter(GeneratedVariableElement.newParameter(
      "values", new PointerType(componentType), methodElement));
  methodElement.addParameter(GeneratedVariableElement.newParameter(
      "count", typeUtil.getInt(), methodElement));
  if (!componentType.getKind().isPrimitive()) {
    methodElement.addParameter(GeneratedVariableElement.newParameter(
        "type", TypeUtil.IOS_CLASS.asType(), methodElement));
  }
  MethodInvocation invocation = new MethodInvocation(
      new ExecutablePair(methodElement), arrayType, new SimpleName(iosArrayElement));

  // Create the array initializer and add it as the first parameter.
  ArrayInitializer arrayInit = new ArrayInitializer(arrayType);
  for (Expression element : elements) {
    arrayInit.addExpression(element.copy());
  }
  invocation.addArgument(arrayInit);

  // Add the array size parameter.
  invocation.addArgument(
      NumberLiteral.newIntLiteral(arrayInit.getExpressions().size(), typeUtil));

  // Add the type argument for object arrays.
  if (!componentType.getKind().isPrimitive()) {
    invocation.addArgument(new TypeLiteral(componentType, typeUtil));
  }

  return invocation;
}
 
Example #25
Source Project: openjdk-jdk9   Author: AdoptOpenJDK   File: GeneratedPlugin.java    License: GNU General Public License v2.0 5 votes vote down vote up
public void register(PrintWriter out) {
    out.printf("        plugins.register(new %s(", pluginName);
    if (needInjectionProvider) {
        out.printf("injection");
    }
    out.printf("), %s.class, \"%s\"", intrinsicMethod.getEnclosingElement(), intrinsicMethod.getSimpleName());
    if (!intrinsicMethod.getModifiers().contains(Modifier.STATIC)) {
        out.printf(", InvocationPlugin.Receiver.class");
    }
    for (VariableElement arg : intrinsicMethod.getParameters()) {
        out.printf(", %s.class", getErasedType(arg.asType()));
    }
    out.printf(");\n");
}
 
Example #26
Source Project: netbeans   Author: apache   File: EnableBeansFilter.java    License: Apache License 2.0 5 votes vote down vote up
private boolean hasModifier ( Element element , Modifier mod){
    Set<Modifier> modifiers = element.getModifiers();
    for (Modifier modifier : modifiers) {
        if ( modifier.equals( mod )){
            return true;
        }
    }
    return false;
}
 
Example #27
Source Project: netbeans   Author: apache   File: Common.java    License: Apache License 2.0 5 votes vote down vote up
public static MethodTree createMethod(TreeMaker make,String name, Map<String,String> params) {
    ModifiersTree methodModifiers = make.Modifiers(
            Collections.<Modifier>singleton(Modifier.PUBLIC),
            Collections.<AnnotationTree>emptyList()
            );
    List<VariableTree> paramList = new LinkedList<VariableTree>();
    for(String paramName: params.keySet()) {
        Tree paramType = getTreeForType(params.get(paramName), make);
        VariableTree parameter = make.Variable(
                make.Modifiers(
                Collections.<Modifier>emptySet(),
                Collections.<AnnotationTree>emptyList()
                ),
                paramName, // name
                paramType, // parameter type
                null // initializer - does not make sense in parameters.
                );
        paramList.add(parameter);
    }
    MethodTree newMethod = make.Method(
            methodModifiers, // public
            name, // name
            make.PrimitiveType(TypeKind.VOID), // return type "void"
            Collections.<TypeParameterTree>emptyList(), // type parameters - none
            paramList, // final ObjectOutput arg0
            Collections.<ExpressionTree>emptyList(), // throws
            "{ throw new UnsupportedOperationException(\"Not supported yet.\") }", // body text
            null // default value - not applicable here, used by annotations
            );
    return newMethod;
}
 
Example #28
Source Project: java-n-IDE-for-Android   Author: shenghuntianlang   File: ModifierOrderer.java    License: Apache License 2.0 5 votes vote down vote up
/**
     * Returns the {@link Modifier} for the given token kind, or {@code
     * null}.
     */
    private static Modifier getModifier(TokenKind kind) {
        if (kind == null) {
            return null;
        }
        switch (kind) {
            case PUBLIC:
                return Modifier.PUBLIC;
            case PROTECTED:
                return Modifier.PROTECTED;
            case PRIVATE:
                return Modifier.PRIVATE;
            case ABSTRACT:
                return Modifier.ABSTRACT;
            case STATIC:
                return Modifier.STATIC;
            // TODO: 22-Jul-17 unsupported lambdas expr
//            case DEFAULT:
//                return Modifier.DEFAULT;
            case FINAL:
                return Modifier.FINAL;
            case TRANSIENT:
                return Modifier.TRANSIENT;
            case VOLATILE:
                return Modifier.VOLATILE;
            case SYNCHRONIZED:
                return Modifier.SYNCHRONIZED;
            case NATIVE:
                return Modifier.NATIVE;
            case STRICTFP:
                return Modifier.STRICTFP;
            default:
                return null;
        }
    }
 
Example #29
Source Project: hottub   Author: dsrg-uoft   File: PubapiVisitor.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Override
public Void visitType(TypeElement e, Void p) {
    if (e.getModifiers().contains(Modifier.PUBLIC)
        || e.getModifiers().contains(Modifier.PROTECTED))
    {
        sb.append(depth(indent) + "TYPE " + e.getQualifiedName() + "\n");
        indent += 2;
        Void v = super.visitType(e, p);
        indent -= 2;
        return v;
    }
    return null;
}
 
Example #30
Source Project: aws-sdk-java-v2   Author: aws   File: ClientClassUtils.java    License: Apache License 2.0 5 votes vote down vote up
static MethodSpec applySignerOverrideMethod(PoetExtensions poetExtensions, IntermediateModel model) {
    String signerOverrideVariable = "signerOverride";

    TypeVariableName typeVariableName =
        TypeVariableName.get("T", poetExtensions.getModelClass(model.getSdkRequestBaseClassName()));

    ParameterizedTypeName parameterizedTypeName = ParameterizedTypeName
        .get(ClassName.get(Consumer.class), ClassName.get(AwsRequestOverrideConfiguration.Builder.class));

    CodeBlock codeBlock = CodeBlock.builder()
                                   .beginControlFlow("if (request.overrideConfiguration().flatMap(c -> c.signer())"
                                                     + ".isPresent())")
                                   .addStatement("return request")
                                   .endControlFlow()
                                   .addStatement("$T $L = b -> b.signer(signer).build()",
                                                 parameterizedTypeName,
                                                 signerOverrideVariable)
                                   .addStatement("$1T overrideConfiguration =\n"
                                                 + "            request.overrideConfiguration().map(c -> c.toBuilder()"
                                                 + ".applyMutation($2L).build())\n"
                                                 + "            .orElse((AwsRequestOverrideConfiguration.builder()"
                                                 + ".applyMutation($2L).build()))",
                                                 AwsRequestOverrideConfiguration.class,
                                                 signerOverrideVariable)
                                   .addStatement("return (T) request.toBuilder().overrideConfiguration"
                                                 + "(overrideConfiguration).build()")
                                   .build();

    return MethodSpec.methodBuilder("applySignerOverride")
                     .addModifiers(Modifier.PRIVATE)
                     .addParameter(typeVariableName, "request")
                     .addParameter(Signer.class, "signer")
                     .addTypeVariable(typeVariableName)
                     .addCode(codeBlock)
                     .returns(typeVariableName)
                     .build();
}