Creates the code by type.

@param type the type
@param topLevelClass the top level class
@param packageName the package name
@param mappedUniName the mapped uni name
@param isUniName the is uni name
@return the code dependent
552612
private static CodeDependent createCodeByType(EnumElement type, boolean topLevelClass, String packageName,
            Map<String, String> mappedUniName, boolean isUniName) {

        CodeDependent cd = new CodeDependent();

        String defaultClsName = type.name();
        String simpleName = getProxyClassName(defaultClsName, mappedUniName, isUniName);

        // To generate class
        StringBuilder code = new StringBuilder();
        if (topLevelClass) {
            // define package
            code.append("package ").append(packageName).append(CODE_END);
            code.append("\n");
            // add import;
            code.append("import com.baidu.bjf.remoting.protobuf.EnumReadable;\n");
        }

        // define class
        // define class
        if (topLevelClass) {
            code.append("public enum ");
        } else {
            code.append("public static enum ");
        }
        code.append(simpleName).append(" implements EnumReadable {\n");

        Iterator<EnumConstantElement> iter = type.constants().iterator();
        while (iter.hasNext()) {
            EnumConstantElement value = iter.next();
            String name = value.name();
            int tag = value.tag();

            code.append(name).append("(").append(tag).append(")");
            if (iter.hasNext()) {
                code.append(",");
            } else {
                code.append(";\n");
            }
        }

        code.append("private final int value;\n");
        code.append(simpleName).append("(int value) { this.value = value;  }\n");
        code.append("public int value() { return value; }\n");
        code.append("}\n");

        cd.name = simpleName;
        cd.pkg = packageName;
        cd.code = code.toString();

        return cd;
    }
671261
private void processEntityClass(TopLevelClass topLevelClass, IntrospectedTable introspectedTable) {
        //引入JPA注解
        topLevelClass.addImportedType("javax.persistence.*");
        //lombok扩展开始
        //如果需要Data，引入包，代码增加注解
        if (this.needsData) {
            topLevelClass.addImportedType("lombok.Data");
            topLevelClass.addAnnotation("@Data");
        }
        //如果需要Getter，引入包，代码增加注解
        if (this.needsGetter) {
            topLevelClass.addImportedType("lombok.Getter");
            topLevelClass.addAnnotation("@Getter");
        }
        //如果需要Setter，引入包，代码增加注解
        if (this.needsSetter) {
            topLevelClass.addImportedType("lombok.Setter");
            topLevelClass.addAnnotation("@Setter");
        }
        //如果需要ToString，引入包，代码增加注解
        if (this.needsToString) {
            topLevelClass.addImportedType("lombok.ToString");
            topLevelClass.addAnnotation("@ToString");
        }
        //如果需要Getter，引入包，代码增加注解
        if (this.needsAccessors) {
            topLevelClass.addImportedType("lombok.experimental.Accessors");
            topLevelClass.addAnnotation("@Accessors(chain = true)");
        }
        //如果需要Getter，引入包，代码增加注解
        if (this.needsEqualsAndHashCode) {
            topLevelClass.addImportedType("lombok.EqualsAndHashCode");
            topLevelClass.addAnnotation("@EqualsAndHashCode");
        }
        //lombok扩展结束
        // region swagger扩展
        if (this.needsSwagger) {
            //导包
            topLevelClass.addImportedType("io.swagger.annotations.ApiModel");
            topLevelClass.addImportedType("io.swagger.annotations.ApiModelProperty");
            //增加注解(去除注释中的转换符)
            String remarks = introspectedTable.getRemarks();
            if (remarks == null) {
                remarks = "";
            }
            topLevelClass.addAnnotation("@ApiModel(\"" + remarks.replaceAll("\r", "").replaceAll("\n", "") + "\")");
        }
        // endregion swagger扩展
        String tableName = introspectedTable.getFullyQualifiedTableNameAtRuntime();
        //如果包含空格，或者需要分隔符，需要完善
        if (StringUtility.stringContainsSpace(tableName)) {
            tableName = context.getBeginningDelimiter()
                    + tableName
                    + context.getEndingDelimiter();
        }
        //是否忽略大小写，对于区分大小写的数据库，会有用
        if (caseSensitive && !topLevelClass.getType().getShortName().equals(tableName)) {
            topLevelClass.addAnnotation("@Table(name = \"" + getDelimiterName(tableName) + "\")");
        } else if (!topLevelClass.getType().getShortName().equalsIgnoreCase(tableName)) {
            topLevelClass.addAnnotation("@Table(name = \"" + getDelimiterName(tableName) + "\")");
        } else if (StringUtility.stringHasValue(schema)
                || StringUtility.stringHasValue(beginningDelimiter)
                || StringUtility.stringHasValue(endingDelimiter)) {
            topLevelClass.addAnnotation("@Table(name = \"" + getDelimiterName(tableName) + "\")");
        } else if (forceAnnotation) {
            topLevelClass.addAnnotation("@Table(name = \"" + getDelimiterName(tableName) + "\")");
        }
        if (generateColumnConsts) {
            for (IntrospectedColumn introspectedColumn : introspectedTable.getAllColumns()) {
                Field field = new Field();
                field.setVisibility(JavaVisibility.PUBLIC);
                field.setStatic(true);
                field.setFinal(true);
                field.setName(introspectedColumn.getActualColumnName().toUpperCase()); //$NON-NLS-1$
                field.setType(new FullyQualifiedJavaType(String.class.getName())); //$NON-NLS-1$
                field.setInitializationString("\"" + introspectedColumn.getJavaProperty() + "\"");
                context.getCommentGenerator().addClassComment(topLevelClass, introspectedTable);
                topLevelClass.addField(field);
                //增加字段名常量,用于pageHelper
                Field columnField = new Field();
                columnField.setVisibility(JavaVisibility.PUBLIC);
                columnField.setStatic(true);
                columnField.setFinal(true);
                columnField.setName("DB_" + introspectedColumn.getActualColumnName().toUpperCase()); //$NON-NLS-1$
                columnField.setType(new FullyQualifiedJavaType(String.class.getName())); //$NON-NLS-1$
                columnField.setInitializationString("\"" + introspectedColumn.getActualColumnName() + "\"");
                topLevelClass.addField(columnField);
            }
        }
        if (generateDefaultInstanceMethod) {
            Method defaultMethod = new Method();
            defaultMethod.setStatic(true);
            defaultMethod.setName("defaultInstance");
            defaultMethod.setVisibility(JavaVisibility.PUBLIC);
            defaultMethod.setReturnType(topLevelClass.getType());
            defaultMethod.addBodyLine(String.format("%s instance = new %s();", topLevelClass.getType().getShortName(), topLevelClass.getType().getShortName()));
            for (IntrospectedColumn introspectedColumn : introspectedTable.getAllColumns()) {
                String shortName = introspectedColumn.getFullyQualifiedJavaType().getShortName();
                List<String> supportType = Arrays.asList("Byte", "Short", "Character", "Integer", "Long", "Float", "Double", "String", "BigDecimal", "BigInteger");
                if (!supportType.contains(shortName)) {
                    continue;
                }
                if (introspectedColumn.getDefaultValue() != null) {
                    String defaultValue = introspectedColumn.getDefaultValue();
                    //去除前后'',如 '123456' -> 123456
                    if (defaultValue.startsWith("'") && defaultValue.endsWith("'")) {
                        if (defaultValue.length() == 2) {
                            defaultValue = "";
                        } else {
                            defaultValue = defaultValue.substring(1, defaultValue.length() - 1);
                        }
                    }
                    //暂不支持时间类型默认值识别,不同数据库表达式不同
                    if ("Boolean".equals(shortName)) {
                        if ("0".equals(defaultValue)) {
                            defaultValue = "false";
                        } else if ("1".equals(defaultValue)) {
                            defaultValue = "true";
                        }
                    }
                    //通过 new 方法转换
                    defaultMethod.addBodyLine(String.format("instance.%s = new %s(\"%s\");", introspectedColumn.getJavaProperty(), shortName, defaultValue));
                }

            }
            defaultMethod.addBodyLine("return instance;");
            topLevelClass.addMethod(defaultMethod);
        }
    }
84448
public static boolean isSARLAnnotation(Class<?> type) {
		return (type != null && Annotation.class.isAssignableFrom(type))
				&& isSARLAnnotation(type.getPackage().getName());
	}
1065440
public void addUpperConstraint(String type) {
		final JvmUpperBound constraint = this.jvmTypesFactory.createJvmUpperBound();
		constraint.setTypeReference(newTypeRef(this.context, type));
		getJvmTypeParameter().getConstraints().add(constraint);
	}
1118374
public static boolean isJavaBasicType(@Nullable Class<?> type) {
        if (type == null) {
            return false;
        }
        final String name = type.getName();
        return isJavaBasicType(name);
    }
1171213
public static Type resolveGenericType(Type initialType, Class<?> targetType) {
        Class<?> rawType;
        if (initialType instanceof ParameterizedType)
            rawType = (Class<?>) ((ParameterizedType) initialType).getRawType();
        else
            rawType = (Class<?>) initialType;

        if (targetType.equals(rawType))
            return initialType;

        Type result;
        if (targetType.isInterface()) {
            for (Type superInterface : rawType.getGenericInterfaces())
                if (superInterface != null && !superInterface.equals(Object.class))
                    if ((result = resolveGenericType(superInterface, targetType)) != null)
                        return result;
        }

        Type superType = rawType.getGenericSuperclass();
        if (superType != null && !superType.equals(Object.class))
            if ((result = resolveGenericType(superType, targetType)) != null)
                return result;

        return null;
    }
1019269
public static Condition<?, ?> isType(final Class<?> type) {
    return new Condition<Object, Object>() {
      public boolean applies(MappingContext<Object, Object> context) {
        return type.isAssignableFrom(context.getSourceType());
      }
    };
  }
881797
@Override
  public ITypeRef create( IType type )
  {
    // already a proxy? return as is then
    if( type instanceof ITypeRef )
    {
      return (ITypeRef)type;
    }

    if( type instanceof INonLoadableType )
    {
      throw new UnsupportedOperationException( "Type references are not supported for nonloadable types: " + type.getName() );
    }

    String strTypeName = TypeLord.getNameWithQualifiedTypeVariables( type, true );
    if( strTypeName == null || strTypeName.length() == 0 )
    {
      throw new IllegalStateException( "Type has no name" );
    }

    ITypeRef ref;
    if (ExecutionMode.isRuntime()) {
      ref = getRefTheFastWay(type, strTypeName);
    } else {
      ref = getRefTheSafeWay(type, strTypeName);
    }
    return ref;
  }
511028
public static String renderPackage(final Class<?> type) {
        return PACKAGE_FORMATTER.abbreviate(type.isMemberClass() && !type.isAnonymousClass()
                ? type.getDeclaringClass().getName() : type.getPackage().getName());
    }
892030
@Override
    <T> Class<T> loadClass(final Class<T> superclassOrInterfaceType) {
        final Class<?> type = getType();
        if (!superclassOrInterfaceType.isAssignableFrom(type)) {
            throw new IllegalArgumentException(
                    "Primitive class " + baseType + " cannot be cast to " + superclassOrInterfaceType.getName());
        }
        @SuppressWarnings("unchecked")
        final Class<T> classT = (Class<T>) type;
        return classT;
    }
855975
private static JClassType findFirstTypeToApplyPropertyAnnotation( List<JMapperType> mapperTypeList ) {
        if ( mapperTypeList.isEmpty() ) {
            return null;
        }

        List<JMapperType> subLevel = new ArrayList<JMapperType>();
        for ( JMapperType mapperType : mapperTypeList ) {
            if ( mapperType.isBeanMapper() ) {
                return mapperType.getType().isClass();
            } else if ( mapperType.getParameters().size() > 0 ) {
                subLevel.addAll( mapperType.getParameters() );
            }
        }

        return findFirstTypeToApplyPropertyAnnotation( subLevel );
    }
996942
public static QualifiedName of(String packageName, String topLevelType, String... nestedTypes) {
    requireNonNull(!packageName.isEmpty());
    checkArgument(!topLevelType.isEmpty());
    return new QualifiedName(
        unshadedName(packageName),  // shadowJar modifies string literals; unshade them here
        ImmutableList.<String>builder().add(topLevelType).add(nestedTypes).build());
  }
1302709
@SuppressWarnings({"unchecked"})
  public static <T extends MessageBundle> T create(final Class<T> type) {
    checkNotNull(type);
    return (T) Proxy.newProxyInstance(type.getClassLoader(), new Class[]{type}, new Handler(type));
  }
811949
private static boolean isNestedTypeDependency(String type, List<TypeElement> nestedTypes,
            Map<String, String> mappedUniName, boolean isUniName) {
        if (nestedTypes == null) {
            return false;
        }

        for (TypeElement t : nestedTypes) {
            if (type.equals(t.name()) || type.equals(getProxyClassName(t.name(), mappedUniName, isUniName))) {
                return true;
            }
        }

        return false;
    }
111303
GeneratedType analyse(TypeElement type) throws CannotGenerateCodeException {
    PackageElement pkg = elements.getPackageOf(type);
    verifyType(type, pkg);
    QualifiedName generatedBuilder = QualifiedName.of(
        pkg.getQualifiedName().toString(), generatedBuilderSimpleName(type));
    List<? extends TypeParameterElement> typeParameters = type.getTypeParameters();
    DeclaredType builder = tryFindBuilder(generatedBuilder, type).orElse(null);
    if (builder == null) {
      return new GeneratedStub(
        QualifiedName.of(type),
        generatedBuilder.withParameters(typeParameters));
    }

    ImmutableSet<ExecutableElement> methods = methodsOn(type, elements, errorType -> {
      throw new CannotGenerateCodeException();
    });
    Datatype.Builder constructionAndExtension = constructionAndExtension(builder);
    QualifiedName valueType = generatedBuilder.nestedType("Value");
    QualifiedName partialType = generatedBuilder.nestedType("Partial");
    QualifiedName propertyType = generatedBuilder.nestedType("Property");
    Datatype.Builder datatypeBuilder = new Datatype.Builder()
        .setType(QualifiedName.of(type).withParameters(typeParameters))
        .setInterfaceType(type.getKind().isInterface())
        .mergeFrom(constructionAndExtension)
        .setGeneratedBuilder(generatedBuilder.withParameters(typeParameters))
        .setValueType(valueType.withParameters(typeParameters))
        .setPartialType(partialType.withParameters(typeParameters))
        .setPropertyEnum(propertyType.withParameters())
        .putAllStandardMethodUnderrides(findUnderriddenMethods(methods))
        .setHasToBuilderMethod(hasToBuilderMethod(
            builder, constructionAndExtension.isExtensible(), methods))
        .setBuilderSerializable(shouldBuilderBeSerializable(builder))
        .setBuilder(Type.from(builder));
    if (datatypeBuilder.getBuilderFactory().isPresent()
        && !datatypeBuilder.getHasToBuilderMethod()) {
      datatypeBuilder.setRebuildableType(
          generatedBuilder.nestedType("Rebuildable").withParameters(typeParameters));
    }
    Datatype baseDatatype = datatypeBuilder.build();
    Map<Property, PropertyCodeGenerator> generatorsByProperty = pickPropertyGenerators(
        type, baseDatatype, builder, removeNonGetterMethods(builder, methods));
    datatypeBuilder.mergeFrom(gwtMetadata(type, baseDatatype, generatorsByProperty));
    return new GeneratedBuilder(datatypeBuilder.build(), generatorsByProperty);
  }
47756
private static Class<?> getRawClass(Type type) {
    if (type instanceof Class) {
      return (Class<?>) type;
    }
    if (type instanceof ParameterizedType) {
      return getRawClass(((ParameterizedType) type).getRawType());
    }
    // For TypeVariable and WildcardType, returns the first upper bound.
    if (type instanceof TypeVariable) {
      return getRawClass(((TypeVariable) type).getBounds()[0]);
    }
    if (type instanceof WildcardType) {
      return getRawClass(((WildcardType) type).getUpperBounds()[0]);
    }
    if (type instanceof GenericArrayType) {
      Class<?> componentClass = getRawClass(((GenericArrayType) type).getGenericComponentType());
      return Array.newInstance(componentClass, 0).getClass();
    }
    // This shouldn't happen as we captured all implementations of Type above (as or Java 8)
    throw new IllegalArgumentException("Unsupported type " + type + " of type class " + type.getClass());
  }
170370
public synchronized <T extends TopLevelItem> T createProject( Class<T> type, String name ) throws IOException {
        return type.cast(createProject((TopLevelItemDescriptor)getDescriptor(type),name));
    }