Java 类javax.lang.model.element.Modifier 实例源码

项目:incubator-netbeans    文件:Tiny.java   
private static boolean isSynced(HintContext ctx, TreePath inspect) {
    while (inspect != null && !TreeUtilities.CLASS_TREE_KINDS.contains(inspect.getLeaf().getKind())) {
        if (inspect.getLeaf().getKind() == Kind.SYNCHRONIZED) {
            return true;
        }

        if (inspect.getLeaf().getKind() == Kind.METHOD) {
            if (((MethodTree) inspect.getLeaf()).getModifiers().getFlags().contains(Modifier.SYNCHRONIZED)) {
                return true;
            }

            break;
        }

        inspect = inspect.getParentPath();
    }

    return false;
}
项目:jso-builder    文件:SerializerGenerator.java   
private MethodSpec createToJSONMethod() {
    return MethodSpec.methodBuilder("toJSON")
            .addModifiers(Modifier.FINAL)
            .addAnnotation(ClassNames.GWT_INCOMPATIBLE)
            .addParameter(Object.class, "object")
            .returns(String.class)
            .beginControlFlow("if (!isJsObject(object.getClass()))")
                .addStatement("throw new $T($S + object.getClass() + $S)", IllegalStateException.class,
                        "Class ", " isn't a JavaScript object")
            .endControlFlow()
            .addStatement("$T writer = new $T()", StringWriter.class, StringWriter.class)
            .beginControlFlow("try")
                .addStatement("writeJSON(writer, object)")
            .nextControlFlow("catch ($T e)", IOException.class)
                .addStatement("throw new $T(e)", RuntimeException.class)
            .endControlFlow()
            .addStatement("return writer.toString()")
            .build();
}
项目:json2java4idea    文件:ModelClassBuilder.java   
@Nonnull
@Override
protected List<FieldSpec> buildFields() {
    return getProperties()
            .entrySet()
            .stream()
            .map(property -> {
                final String name = property.getKey();
                final TypeName type = property.getValue();
                final String fieldName = fieldNamePolicy.convert(name, type);
                return FieldSpec.builder(type, fieldName)
                        .addModifiers(Modifier.PRIVATE, Modifier.FINAL)
                        .build();
            })
            .collect(Collectors.toList());
}
项目:incubator-netbeans    文件:ImportAnalysisTest.java   
public void testImportGetterSetter() throws IOException {
    testFile = getFile(getSourceDir(), getSourcePckg() + "ImportsTest8.java");
    JavaSource src = getJavaSource(testFile);
    Task<WorkingCopy> task = new Task<WorkingCopy>() {

        public void run(WorkingCopy workingCopy) throws IOException {
            workingCopy.toPhase(Phase.RESOLVED);
            CompilationUnitTree cut = workingCopy.getCompilationUnit();
            TreeMaker make = workingCopy.getTreeMaker();
            ClassTree clazz = (ClassTree) cut.getTypeDecls().get(0);
            ExpressionTree type = make.QualIdent(workingCopy.getElements().getTypeElement("java.awt.geom.Point2D.Double"));
            VariableTree vt = make.Variable(make.Modifiers(EnumSet.noneOf(Modifier.class)), "test",type, null);
            workingCopy.rewrite(clazz, make.addClassMember(clazz, vt));
        }
    };
    src.runModificationTask(task).commit();
    assertFiles("testImportGetterSetter.pass");
}
项目:aws-sdk-java-v2    文件:ModelBuilderSpecs.java   
private MethodSpec modelCopyConstructor() {
    MethodSpec.Builder copyBuilderCtor = MethodSpec.constructorBuilder()
            .addModifiers(Modifier.PRIVATE)
            .addParameter(classToBuild(), "model");

    shapeModel.getNonStreamingMembers().forEach(m -> {
        String name = m.getVariable().getVariableName();
        copyBuilderCtor.addStatement("$N(model.$N)", m.getFluentSetterMethodName(), name);
    });

    if (isException()) {
        copyBuilderCtor.addStatement("this.message = model.getMessage()");
    }

    return copyBuilderCtor.build();
}
项目:incubator-netbeans    文件:ConvertToLambdaPreconditionChecker.java   
@Override
public Tree visitNewClass(NewClassTree node, Trees p) {
    Tree t = super.visitNewClass(node, p);
    // new class tree > expression statement tree > block. Does not accept anonymous classes for ctor references.
    if (node.getClassBody() == null && singleStatementLambdaMethodBody == getCurrentPath().getParentPath().getParentPath().getLeaf()) {
        Tree parent = getCurrentPath().getParentPath().getLeaf();
        Element el = info.getTrees().getElement(getCurrentPath());
        if (el == null || el.getKind() != ElementKind.CONSTRUCTOR || !el.getEnclosingElement().getKind().isClass()) {
            return t;
        }
        el = el.getEnclosingElement();
        if (parent.getKind() == Tree.Kind.EXPRESSION_STATEMENT || parent.getKind() == Tree.Kind.RETURN) {
            ExpressionTree et = node.getEnclosingExpression();
            if (et != null) {
                if (el.getModifiers().contains(Modifier.STATIC) || !isMeaninglessQualifier(new TreePath(getCurrentPath().getParentPath(), et))) {
                    return t;
                }
            }
            foundConstructorReferenceCandidate = true;
        }
    }
    return t;
}
项目:incubator-netbeans    文件:ImportAnalysisTest.java   
public void test157566b() throws IOException {
    testFile = getFile(getSourceDir(), "org/netbeans/test/codegen/imports157566/b/Test.java");
    JavaSource src = getJavaSource(testFile);
    Task<WorkingCopy> task = new Task<WorkingCopy>() {
        public void run(WorkingCopy workingCopy) throws IOException {
            workingCopy.toPhase(Phase.RESOLVED);
            CompilationUnitTree cut = workingCopy.getCompilationUnit();
            TreeMaker make = workingCopy.getTreeMaker();
            ClassTree clazz = (ClassTree) cut.getTypeDecls().get(0);
            final TypeElement foo = workingCopy.getElements().getTypeElement("org.netbeans.test.codegen.imports157566.b.String");
            assertNotNull(foo);
            Tree type = make.QualIdent(foo);
            VariableTree vt = make.Variable(make.Modifiers(EnumSet.noneOf(Modifier.class)), "test", type, null);
            workingCopy.rewrite(clazz, make.addClassMember(clazz, vt));
        }
    };
    src.runModificationTask(task).commit();
    assertFiles("testImports157566b.pass");
}
项目:Alligator    文件:NavigationFactoryGenerator.java   
public JavaFile generate(List<RegistrationAnnotatedClass> annotatedClasses) throws ProcessingException {
    MethodSpec.Builder constructorBuilder = MethodSpec.constructorBuilder()
            .addModifiers(Modifier.PUBLIC);

    for (RegistrationAnnotatedClass annotatedClass : annotatedClasses) {
        ClassName annotatedClassName = ClassName.get(annotatedClass.getClassElement());
        ClassName screenClassName = ClassName.bestGuess(annotatedClass.getScreenClassName());

        if (annotatedClass.getScreenResultClassName() == null) {
            String registrationMethod = getRegistrationMethod(annotatedClass.getScreenType());
            constructorBuilder.addStatement(registrationMethod, screenClassName, annotatedClassName);
        } else {
            String registrationForResultMethod = getRegistrationForResultMethod(annotatedClass.getScreenType());
            ClassName screenResultClassName = ClassName.bestGuess(annotatedClass.getScreenResultClassName());
            constructorBuilder.addStatement(registrationForResultMethod, screenClassName, annotatedClassName, screenResultClassName);
        }
    }

    TypeSpec navigationFactory = TypeSpec.classBuilder(CLASS_NAME)
            .addModifiers(Modifier.PUBLIC)
            .superclass(ClassName.get(PACKAGE, SUPERCLASS_NAME))
            .addMethod(constructorBuilder.build())
            .build();

    return JavaFile.builder(PACKAGE, navigationFactory).build();
}
项目:incubator-netbeans    文件:ControllerGenerator.java   
/**
 * Defines a new method as event handler, and marks it with @FXML annotation.
 * 
 * @param h handler definition
 */
private void defineNewHandler(CharSequence handlerName, TypeElement eventType) {
    TreeMaker mk = wcopy.getTreeMaker();

    // @FXML private void {handlerName}({eventType} event);
    MethodTree handler = mk.Method(
            mk.Modifiers(Collections.singleton(Modifier.PRIVATE), 
                Collections.singletonList(fxmlAnnotationTree)
            ),
            handlerName, 
            mk.PrimitiveType(TypeKind.VOID),
            Collections.<TypeParameterTree>emptyList(),
            Collections.singletonList(
                mk.Variable(
                    mk.Modifiers(Collections.<Modifier>emptySet()), 
                    "event", mk.Type(eventType.asType()), null)
            ), 
            Collections.<ExpressionTree>emptyList(),
            mk.Block(Collections.<StatementTree>emptyList(), false), 
            null);

    // add to class
    controllerClass = genUtils().insertClassMember(controllerClass, handler);
    addMethod(handlerName.toString(), eventType.asType());
}
项目:incubator-netbeans    文件:IntroduceHintTest.java   
public void testConstantFix208072c() throws Exception {
    Preferences prefs = CodeStylePreferences.get((FileObject) null, JavacParser.MIME_TYPE).getPreferences();
    prefs.put("classMembersOrder", "STATIC_INIT;STATIC METHOD;INSTANCE_INIT;CONSTRUCTOR;METHOD;STATIC CLASS;CLASS;STATIC FIELD;FIELD");
    prefs.put("classMemberInsertionPoint", "LAST_IN_CATEGORY");
    performFixTest("package test;\n" +
                   "import java.util.logging.Level;\n" +
                   "import java.util.logging.Logger;\n" +
                   "public class Test {\n" +
                   "     {\n" +
                   "         int ii = |1 + 2 * 3|;\n" +
                   "     }\n" +
                   "     private static final int II = 0;\n" +
                   "}\n",
                   ("package test;\n" +
                    "import java.util.logging.Level;\n" +
                    "import java.util.logging.Logger;\n" +
                    "public class Test {\n" +
                   "     {\n" +
                   "         int ii = ZZ;\n" +
                   "     }\n" +
                   "     private static final int II = 0;\n" +
                   "     private static final int ZZ = 1 + 2 * 3;\n" +
                    "}\n").replaceAll("[ \t\n]+", " "),
                   new DialogDisplayerImpl("ZZ", true, true, true, EnumSet.of(Modifier.PRIVATE)),
                   5, 1);
}
项目:incubator-netbeans    文件:JavaUtil.java   
public static void addInputParamFields(JavaSource source,
        final List<ParameterInfo> params,
        final javax.lang.model.element.Modifier[] modifier) throws IOException {
    ModificationResult result = source.runModificationTask(new AbstractTask<WorkingCopy>() {

        public void run(WorkingCopy copy) throws IOException {
            copy.toPhase(JavaSource.Phase.ELEMENTS_RESOLVED);
            List<ParameterInfo> addList = new ArrayList<ParameterInfo>();
            for (ParameterInfo p : params) {
                if (JavaSourceHelper.getField(copy, Util.getParameterName(p, true, true, true)) == null) {
                    addList.add(p);
                }
            }
            JavaSourceHelper.addFields(copy, Util.getParamNames(addList),
                    Util.getParamTypeNames(addList), Util.getParamValues(addList), modifier);
        }
    });
    result.commit();
}
项目:incubator-netbeans    文件:IntroduceHintTest.java   
public void testIntroduceMethodReplaceDuplicatesSimpleRemapNotUseAfterMethod() throws Exception {
    performFixTest("package test;\n" +
                   "public class Test {\n" +
                   "    public static void test1() {\n" +
                   "        int i = 0;\n" +
                   "        |System.err.println(i);|\n" +
                   "    }\n" +
                   "    public static void test2() {\n" +
                   "        int a = 0;\n" +
                   "        System.err.println(a);\n" +
                   "    }\n" +
                   "}",
                   "package test; public class Test { public static void test1() { int i = 0; name(i); } public static void test2() { int a = 0; name(a); } private static void name(int i) { System.err.println(i); } }",
                   new DialogDisplayerImpl3("name", EnumSet.of(Modifier.PRIVATE), true, true),
                   1, 0);
}
项目:incubator-netbeans    文件:EnumTest.java   
private void testAddFirstMember(String code, String golden) throws Exception {
    testFile = new File(getWorkDir(), "Test.java");
    TestUtilities.copyStringToFile(testFile, code);
    JavaSource src = getJavaSource(testFile);

    Task<WorkingCopy> task = new Task<WorkingCopy>() {
        public void run(final WorkingCopy workingCopy) throws IOException {
            workingCopy.toPhase(Phase.RESOLVED);
            CompilationUnitTree cut = workingCopy.getCompilationUnit();
            final TreeMaker make = workingCopy.getTreeMaker();

            ModifiersTree mods = make.Modifiers(EnumSet.of(Modifier.PUBLIC));
            Tree ret = make.Type(workingCopy.getTypes().getNoType(TypeKind.VOID));
            MethodTree mt = make.Method(mods, "run", ret, Collections.<TypeParameterTree>emptyList(), Collections.<VariableTree>emptyList(), Collections.<ExpressionTree>emptyList(), "{}", null);

            ClassTree en = (ClassTree) cut.getTypeDecls().get(0);
            workingCopy.rewrite(en, make.addClassMember(en, mt));
        }

    };
    src.runModificationTask(task).commit();
    String res = TestUtilities.copyFileToString(testFile);
    System.err.println(res);
    assertEquals(golden, res);
}
项目:Witch-Android    文件:OnOnBindGetAdapterView.java   
@Override
public String create() {
    MethodSpec method = MethodSpec.methodBuilder("onBind")
            .addModifiers(Modifier.PUBLIC)
            .addParameter(viewType, "target")
            .addParameter(valueType, "value")
            .returns(void.class)
            .addStatement("(($T)$N.getAdapter()).$N(($T)value)", adapterType, "target", getPropertySetter(property), valueType)
            .build();

    TypeSpec anonymous = TypeSpec.anonymousClassBuilder("")
            .addSuperinterface(ParameterizedTypeName
                    .get(TypeUtils.SYNC_ON_BIND, viewType, valueType))
            .addMethod(method)
            .build();

    return anonymous.toString();
}
项目:data-mediator    文件:HashEqualsGenerator.java   
private static void generateHashCode(TypeSpec.Builder typeBuilder, Collection<FieldData> fields,
                                     Collection<FieldData> superFields, boolean hasSuperClass){
    if(fields.isEmpty()){
        return;
    }
    MethodSpec.Builder hashBuilder = MethodSpec.methodBuilder("hashCode")
            .returns(TypeName.INT)
            .addModifiers(Modifier.PUBLIC)
            .addAnnotation(Override.class);

    if(hasSuperClass && !superFields.isEmpty()){
        hashBuilder.addStatement("int result = super.hashCode()");
    }else{
        hashBuilder.addStatement("int result = 0");
    }
    for(FieldData fd : fields){
        addStatementForHashcode(hashBuilder, fd);
    }
    hashBuilder.addStatement("return result");
    sTemp_defined = false;

    typeBuilder.addMethod(hashBuilder.build());
}
项目:incubator-netbeans    文件:DeclarativeHintsParser.java   
private static ClassPath getJavacApiJarClasspath() {
    Reference<ClassPath> r = javacApiClasspath;
    ClassPath res = r.get();
    if (res != null) {
        return res;
    }
    if (r == NONE) {
        return null;
    }
    CodeSource codeSource = Modifier.class.getProtectionDomain().getCodeSource();
    URL javacApiJar = codeSource != null ? codeSource.getLocation() : null;
    if (javacApiJar != null) {
        Logger.getLogger(DeclarativeHintsParser.class.getName()).log(Level.FINE, "javacApiJar={0}", javacApiJar);
        File aj = FileUtil.archiveOrDirForURL(javacApiJar);
        if (aj != null) {
            res = ClassPathSupport.createClassPath(FileUtil.urlForArchiveOrDir(aj));
            javacApiClasspath = new WeakReference<>(res);
            return res;
        }
    }
    javacApiClasspath = NONE;
    return null;
}
项目:auto-value-node    文件:AutoValueNodeProcessor.java   
private MethodSpec generateNodeablePropertyMethod(String propertyTypePackage, String returnTypeSuffix, String methodName, Modifier visibility) {
    MethodSpec.Builder builder = MethodSpec.methodBuilder(methodName)
            .returns(ClassName.get(propertyTypePackage, "Node_" + returnTypeSuffix))
            .addModifiers(Modifier.FINAL)
            .addStatement("return new Node_$L(value == null ? null : value.$L())", returnTypeSuffix, methodName);
    if (visibility != null) {
        builder.addModifiers(visibility);
    }
    return builder.build();
}
项目:shortbread    文件:CodeGenerator.java   
private MethodSpec callMethodShortcut() {
    HashMap<String, List<String>> classMethodsMap = new HashMap<>();

    for (final ShortcutAnnotatedElement annotatedElement : annotatedElements) {
        if (annotatedElement instanceof ShortcutAnnotatedMethod) {
            final ShortcutAnnotatedMethod annotatedMethod = (ShortcutAnnotatedMethod) annotatedElement;
            if (classMethodsMap.containsKey(annotatedMethod.getClassName())) {
                classMethodsMap.get(annotatedElement.getClassName()).add(annotatedMethod.getMethodName());
            } else {
                classMethodsMap.put(annotatedMethod.getClassName(), new ArrayList<String>() {{
                    add(annotatedMethod.getMethodName());
                }});
            }
        }
    }

    final MethodSpec.Builder methodBuilder = MethodSpec.methodBuilder("callMethodShortcut")
            .addModifiers(Modifier.PUBLIC, Modifier.STATIC)
            .returns(void.class)
            .addParameter(activity, "activity");

    for (final Map.Entry<String, List<String>> annotatedMethodName : classMethodsMap.entrySet()) {
        ClassName activityClassName = ClassName.bestGuess(annotatedMethodName.getKey());
        List<String> methodNames = annotatedMethodName.getValue();
        methodBuilder.beginControlFlow("if (activity instanceof $T)", activityClassName);
        for (final String methodName : methodNames) {
            methodBuilder.beginControlFlow("if ($S.equals(activity.getIntent().getStringExtra($S)))", methodName, EXTRA_METHOD);
            methodBuilder.addStatement("(($T) activity).$L()", activityClassName, methodName);
            methodBuilder.endControlFlow();
        }
        methodBuilder.endControlFlow();
    }

    return methodBuilder
            .build();
}
项目:react4j    文件:Generator.java   
@Nonnull
private static MethodSpec.Builder buildRenderAdapterMethod( @Nonnull final MethodDescriptor renderMethod )
{
  return MethodSpec.methodBuilder( "render" ).
    addModifiers( Modifier.PROTECTED ).
    addAnnotation( Override.class ).
    addAnnotation( NULLABLE_CLASSNAME ).
    returns( REACT_NODE_CLASSNAME ).
    addStatement( "return $T.of( $N() )", REACT_NODE_CLASSNAME, renderMethod.getMethod().getSimpleName().toString() );
}
项目:GitHub    文件:RealmBacklinkProcessorTest.java   
@Test
public void ignoreStaticLinkingObjects() throws IOException {
    RealmSyntheticTestClass javaFileObject = createBacklinkTestClass()
            .modifiers(Modifier.PUBLIC, Modifier.STATIC)
            .type("RealmResults")
            .clearAnnotations()
            .annotation("LinkingObjects(\"xxx\")")
            .builder().build();
    ASSERT.about(javaSources())
            .that(Arrays.asList(backlinksTarget, javaFileObject))
            .processedWith(new RealmProcessor())
            .compilesWithoutError();
}
项目:aws-sdk-java-v2    文件:AwsServiceModel.java   
private MethodSpec exceptionConstructor() {
    MethodSpec.Builder ctorBuilder = MethodSpec.constructorBuilder()
                                               .addModifiers(Modifier.PRIVATE)
                                               .addParameter(modelBuilderSpecs.builderImplName(), "builder");

    ctorBuilder.addStatement("super(builder.message)");

    shapeModelSpec.fields().forEach(f -> ctorBuilder.addStatement("this.$N = builder.$N", f, f));

    return ctorBuilder.build();
}
项目:gwt-jackson-apt    文件:DeserializerBuilder.java   
private MethodSpec buildDeserializerMethod(){
    return MethodSpec.methodBuilder( "newDeserializer" )
            .addModifiers( Modifier.PROTECTED )
            .addAnnotation( Override.class )
            .returns( ParameterizedTypeName.get( ClassName.get( JsonDeserializer.class ), DEFAULT_WILDCARD ) )
            .addStatement( "return $L", new FieldDeserializersChainBuilder(beanType).getInstance(field) )
            .build();
}
项目:data-mediator    文件:BaseMemberBuilder.java   
protected MethodSpec.Builder onBuildGet(FieldData field,
                                        String nameForMethod, TypeInfo info) {
    MethodSpec.Builder get = MethodSpec.methodBuilder(field.getGetMethodPrefix() + nameForMethod)
            .returns(info.typeName)
            .addModifiers(Modifier.ABSTRACT, Modifier.PUBLIC);
    return get;
}
项目:GitHub    文件:BaseDecorator.java   
private MethodSpec getAttachViewMethod() {
    MethodSpec.Builder method =
            MethodSpec.methodBuilder(METHOD_ATTACH_VIEW)
                    .addModifiers(Modifier.PUBLIC)
                    .addAnnotation(Override.class)
                    .addParameter(delegateClassGenerator.getViewClass(), "view").returns(TypeName.VOID);
    method.addStatement(
            callPresenterAttachView(FIELD_PRESENTER, "view", "$T"),
            ClassName.bestGuess(delegateClassGenerator.getPresenterViewQualifiedName()));
    return method.build();
}
项目:incubator-netbeans    文件:FieldEncapsulation.java   
private static boolean hasRequiredVisibility(final Set<Modifier> mods, final Modifier reqMod) {
    return reqMod != null ?
        mods.contains(reqMod):
        mods.isEmpty() ?
            true:
            !EnumSet.copyOf(mods).removeAll(EnumSet.of(Modifier.PRIVATE, Modifier.PROTECTED, Modifier.PUBLIC));
}
项目:aws-sdk-java-v2    文件:ClientSimpleMethodsIntegrationTests.java   
/**
 * Creates a setup method for instantiating a new client. If no regions are present for a service,
 * us-east-1 will be used. If the service is available in aws-global, that region will be used. If the
 * service is not available in aws-global but is in us-east-1, that region will be used. If a service is
 * not available in us-east-1 or aws-global, the first region in the available regions for a service will
 * be used.
 */
private MethodSpec setup() {
    ClassName beforeClass = ClassName.get("org.junit", "BeforeClass");
    ClassName interfaceClass = poetExtensions.getClientClass(model.getMetadata().getSyncInterface());
    return MethodSpec.methodBuilder("setup")
                     .addAnnotation(beforeClass)
                     .addModifiers(Modifier.PUBLIC, Modifier.STATIC)
                     .beginControlFlow("if ($T.serviceMetadata().regions().isEmpty())", interfaceClass)
                     .addStatement("client = $T.builder().region($T.US_EAST_1).build()", interfaceClass, Region.class)
                     .endControlFlow()
                     .beginControlFlow("else if ($T.serviceMetadata().regions().contains($T.AWS_GLOBAL))",
                                       interfaceClass,
                                       Region.class)
                     .addStatement("client = $T.builder().region($T.AWS_GLOBAL).build()",
                                   interfaceClass,
                                   Region.class)
                     .endControlFlow()
                     .beginControlFlow("else if ($T.serviceMetadata().regions().contains($T.US_EAST_1))",
                                       interfaceClass,
                                       Region.class)
                     .addStatement("client = $T.builder().region($T.US_EAST_1).build()",
                                   interfaceClass,
                                   Region.class)
                     .endControlFlow()
                     .beginControlFlow("else")
                     .addStatement("client = $1T.builder().region($1T.serviceMetadata().regions().get(0)).build()",
                                   interfaceClass)
                     .endControlFlow()
                     .build();
}
项目:android-auto-mapper    文件:AutoMappperProcessor.java   
private Iterable<FieldSpec> generateFieldSpecs(ImmutableList<Property> properties) {
    List<FieldSpec> fields = new ArrayList<>();
    for (Property property : properties) {
        fields.add(FieldSpec.builder(property.typeName, property.fieldName, new Modifier[]{PUBLIC}).build());
    }

    return fields;
}
项目:aws-sdk-java-v2    文件:SyncClientInterface.java   
/**
 * @return Simple method for streaming output operations to write response content to a file.
 */
private MethodSpec downloadToFileSimpleMethod(OperationModel opModel, TypeName responseType, ClassName requestType) {
    return MethodSpec.methodBuilder(opModel.getMethodName())
                     .returns(responseType)
                     .addModifiers(Modifier.PUBLIC, Modifier.DEFAULT)
                     .addParameter(requestType, opModel.getInput().getVariableName())
                     .addParameter(ClassName.get(Path.class), "filePath")
                     .addJavadoc(opModel.getDocs(model, ClientType.SYNC, SimpleMethodOverload.FILE))
                     .addExceptions(getExceptionClasses(model, opModel))
                     .addStatement("return $L($L, $T.toFile($L))", opModel.getMethodName(),
                                   opModel.getInput().getVariableName(),
                                   ClassName.get(StreamingResponseHandler.class),
                                   "filePath")
                     .build();
}
项目:dataenum    文件:ValueTypeFactory.java   
private static MethodSpec createConstructor(OutputValue value) {
  MethodSpec.Builder constructor = MethodSpec.constructorBuilder().addModifiers(Modifier.PRIVATE);
  for (Parameter parameter : value.parameters()) {
    constructor.addParameter(parameter.type(), parameter.name());

    if (parameter.type().isPrimitive() || parameter.canBeNull()) {
      constructor.addStatement("this.$1L = $1L", parameter.name());
    } else {
      constructor.addStatement("this.$1L = checkNotNull($1L)", parameter.name());
    }
  }
  return constructor.build();
}
项目:GitHub    文件:Constitution.java   
private void lateValidateExtending(TypeElement t) {
  if (t.getModifiers().contains(Modifier.ABSTRACT)) {
    protoclass()
        .report()
        .withElement(t)
        .error("Extending %s shouldn't be abstract, it has to be instantiable",
            t.getSimpleName());
  }

  if (!this.generics.def().equals(generics().def())) {
    protoclass()
        .report()
        .withElement(t)
        .error("Inner type %s should have the same type parameters as abstract value type: %s",
            t.getSimpleName(),
            generics().def());
  }

  if (protoclass().styles().style().stagedBuilder()) {
    protoclass()
        .report()
        .withElement(t)
        .warning("Extending %s shouldn't be used with stagedBuilder style attribute, they are incompartible:"
            + " Staged builder generate series of staged interfaces, but extending builder actually"
            + " extends implementation and do not provide type safety for setting first attribute,"
            + " as well as stagedBuilder forces generated builder interfaces to leak in code using the builder"
            + " and hence defeating the purpose of using extending builder.",
            t.getSimpleName());
  }
}
项目:auto-adapter    文件:ViewBinderGenerator.java   
private TypeSpec.Builder createClassBuilder(final TypeElement model, final ClassName viewBinderClassName) {
    TypeName modelType = ParameterizedTypeName.get(model.asType());
    ParameterizedTypeName viewHolderBinderTypeName = ParameterizedTypeName.get(VIEW_BINDER_NAME, modelType);

    return TypeSpec.classBuilder(viewBinderClassName).addModifiers(Modifier.FINAL).addSuperinterface(
            viewHolderBinderTypeName);
}
项目:aws-sdk-java-v2    文件:SyncClientInterface.java   
private MethodSpec create() {
    return MethodSpec.methodBuilder("create")
                     .returns(className)
                     .addModifiers(Modifier.STATIC, Modifier.PUBLIC)
                     .addJavadoc(
                             "Create a {@link $T} with the region loaded from the {@link $T} and credentials loaded from the "
                             + "{@link $T}.", className, DefaultAwsRegionProviderChain.class,
                             DefaultCredentialsProvider.class)
                     .addStatement("return builder().build()")
                     .build();
}
项目:arez    文件:AutorunDescriptor.java   
/**
 * Build any fields required by
 */
void buildFields( @Nonnull final TypeSpec.Builder builder )
{
  final FieldSpec.Builder field =
    FieldSpec.builder( GeneratorUtil.OBSERVER_CLASSNAME,
                       GeneratorUtil.FIELD_PREFIX + getName(),
                       Modifier.FINAL,
                       Modifier.PRIVATE ).
      addAnnotation( GeneratorUtil.NONNULL_CLASSNAME );
  builder.addField( field.build() );
}
项目:RxAndroidOrm    文件:QueryLoggerGenerator.java   
public TypeSpec generate() {
    return TypeSpec.interfaceBuilder(Constants.QUERY_LOGGER)
            .addModifiers(Modifier.PUBLIC)
            .addMethod(MethodSpec.methodBuilder("onQuery")
                    .addModifiers(Modifier.PUBLIC, Modifier.ABSTRACT)
                    .addParameter(ClassName.get(String.class), "query")
                    .addParameter(ArrayTypeName.get(String[].class), "datas")
                    .build())
            .build();
}
项目:remoter    文件:FieldBuilder.java   
private void addCommonFields(TypeSpec.Builder classBuilder) {
    //Add descriptor
    classBuilder.addField(FieldSpec.builder(ClassName.get(String.class), "DESCRIPTOR")
            .addModifiers(Modifier.PRIVATE, Modifier.STATIC, Modifier.FINAL)
            .initializer("\"" + getRemoterInterfacePackageName() + "." + getRemoterInterfaceClassName() + "\"")
            .build());
    classBuilder.addField(FieldSpec.builder(TypeName.INT, "REMOTER_EXCEPTION_CODE")
            .addModifiers(Modifier.PRIVATE, Modifier.STATIC, Modifier.FINAL)
            .initializer("-99999")
            .build());

}
项目:incubator-netbeans    文件:IntroduceHint.java   
/**
 * Crates method formal parameters, following code style conventions.
 * The trees in 'statements' will be rewritten to use the new identifiers.
 * 
 * @param copy working copy
 * @param parameters variables to turn into parameters
 * @param statements trees that should refer to parameters
 * @return 
 */
static List<VariableTree> createVariables(WorkingCopy copy, List<VariableElement> parameters, 
        TreePath targetParent,
        List<TreePath> statements) {
    final TreeMaker make = copy.getTreeMaker();
    List<VariableTree> formalArguments = new LinkedList<VariableTree>();
    CodeStyle cs = CodeStyle.getDefault(copy.getFileObject());

    String prefix = cs.getParameterNamePrefix();
    String suffix = cs.getParameterNameSuffix(); 
    Map<VariableElement, CharSequence> renamedVariables = new HashMap<VariableElement, CharSequence>();
    Set<Name> changedNames = new HashSet<Name>();
    for (VariableElement p : parameters) {
        TypeMirror tm = p.asType();
        Tree type = make.Type(tm);
        Name formalArgName = p.getSimpleName();
        Set<Modifier> formalArgMods = EnumSet.noneOf(Modifier.class);

        if (p.getModifiers().contains(Modifier.FINAL)) {
            formalArgMods.add(Modifier.FINAL);
        }
        String strippedName = Utilities.stripVariableName(cs, p);
        CharSequence codeStyleName = Utilities.guessName(copy, strippedName, targetParent, prefix, suffix, p.getKind() == ElementKind.PARAMETER);
        if (!formalArgName.contentEquals(codeStyleName)) {
            renamedVariables.put(p, codeStyleName);
            changedNames.add(formalArgName);
        } else {
            codeStyleName = formalArgName;
        }
        formalArguments.add(make.Variable(make.Modifiers(formalArgMods), codeStyleName, type, null));
    }
    if (!changedNames.isEmpty()) {
        VariableRenamer renamer = new VariableRenamer(copy, renamedVariables, changedNames);
        for (TreePath stPath : statements) {
            renamer.scan(stPath, null);
        }
    }
    return formalArguments;
}
项目:annotation-processor-toolkit    文件:ElementUtils_CheckModifierOfElementTest.java   
@Test
public void testHasTransientModifier() {

    Element e = Mockito.mock(Element.class);
    Mockito.when(e.getModifiers()).thenReturn(Utilities.convertVarargsToSet(Modifier.TRANSIENT));
    MatcherAssert.assertThat("Modifier should be found", ElementUtils.CheckModifierOfElement.hasTransientModifier(e));

    Mockito.when(e.getModifiers()).thenReturn(Utilities.convertVarargsToSet(Modifier.PRIVATE));
    MatcherAssert.assertThat("Modifier should not be found", !ElementUtils.CheckModifierOfElement.hasTransientModifier(e));

    // check null valued element
    MatcherAssert.assertThat("Modifier should not be found for null valued elements", !ElementUtils.CheckModifierOfElement.hasTransientModifier(null));

}
项目:resourceprovider    文件:RpCodeGenerator.java   
TypeSpec generateColorProviderClass() {
    MethodSpec constructor = MethodSpec.constructorBuilder()
                                       .addModifiers(PUBLIC)
                                       .addParameter(contextClassName, "context")
                                       .addStatement("this.context = context")
                                       .build();

    TypeSpec.Builder classBuilder = classBuilder("ColorProvider")
            .addModifiers(PUBLIC)
            .addField(contextField)
            .addMethod(constructor)
            .addAnnotation(suppressLint);

    for (String var : rClassColorVars) {
        try {
            classBuilder.addMethod(MethodSpec.methodBuilder("get" + getterSuffix(var))
                                             .addModifiers(Modifier.PUBLIC)
                                             .returns(INT)
                                             .addStatement("return $T.getColor(context, R.color." + var + ")", contextCompatClassName)
                                             .varargs(false)
                                             .build());
        } catch (IllegalArgumentException e) {
            System.out.println("\n\nResourceProvider Compiler Error: " + e.getMessage() + ".\n\nUnable to generate API for R.color." + var + "\n\n") ;
        }
    }

    return classBuilder.build();
}
项目:annotation-processor-toolkit    文件:ElementUtils_CheckModifierOfElementTest.java   
@Test
public void testHasSynchronizedModifier() {

    Element e = Mockito.mock(Element.class);
    Mockito.when(e.getModifiers()).thenReturn(Utilities.convertVarargsToSet(Modifier.SYNCHRONIZED));
    MatcherAssert.assertThat("Modifier should be found", ElementUtils.CheckModifierOfElement.hasSynchronizedModifier(e));

    Mockito.when(e.getModifiers()).thenReturn(Utilities.convertVarargsToSet(Modifier.PRIVATE));
    MatcherAssert.assertThat("Modifier should not be found", !ElementUtils.CheckModifierOfElement.hasSynchronizedModifier(e));

    // check null valued element
    MatcherAssert.assertThat("Modifier should not be found for null valued elements", !ElementUtils.CheckModifierOfElement.hasSynchronizedModifier(null));

}
项目:aws-sdk-java-v2    文件:SyncClientClass.java   
private MethodSpec closeMethod() {
    return MethodSpec.methodBuilder("close")
                     .addAnnotation(Override.class)
                     .addStatement("clientHandler.close()")
                     .addModifiers(Modifier.PUBLIC)
                     .build();
}