com.squareup.javapoet.ClassName.bestGuess()方法的使用及代码示例

x33g5p2x  于2022-01-18 转载在 其他  
字(10.9k)|赞(0)|评价(0)|浏览(290)

本文整理了Java中com.squareup.javapoet.ClassName.bestGuess()方法的一些代码示例,展示了ClassName.bestGuess()的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。ClassName.bestGuess()方法的具体详情如下:
包路径:com.squareup.javapoet.ClassName
类名称:ClassName
方法名:bestGuess

ClassName.bestGuess介绍

[英]Returns a new ClassName instance for the given fully-qualified class name string. This method assumes that the input is ASCII and follows typical Java style (lowercase package names, UpperCamelCase class names) and may produce incorrect results or throw IllegalArgumentException otherwise. For that reason, #get(Class) and #get(Class) should be preferred as they can correctly create ClassNameinstances without such restrictions.
[中]返回给定完全限定类名字符串的新类名实例。此方法假定输入为ASCII,并遵循典型的Java样式(小写包名、大写类名),可能会产生错误的结果或抛出IllegalArgumentException。因此,#get(Class)和#get(Class)应该是首选,因为它们可以在没有此类限制的情况下正确创建ClassNameInstance。

代码示例

代码示例来源:origin: airbnb/epoxy

static ClassName getClassName(String className) {
 return ClassName.bestGuess(className);
}

代码示例来源:origin: square/wire

public AdapterConstant(String adapter) {
 String[] names = adapter.split("#");
 if (names.length != 2) {
  throw new IllegalArgumentException("Illegally formatted adapter: " + adapter + ".");
 }
 this.className = ClassName.bestGuess(names[0]);
 this.memberName = names[1];
}

代码示例来源:origin: facebook/litho

private static ClassName getComponentTypeName(
  String componentClassName, String qualifiedSpecClassName) {
 final String qualifiedComponentClassName;
 if (componentClassName == null || componentClassName.isEmpty()) {
  qualifiedComponentClassName =
    qualifiedSpecClassName.substring(
      0, qualifiedSpecClassName.length() - SPEC_SUFFIX.length());
 } else {
  qualifiedComponentClassName =
    qualifiedSpecClassName.substring(0, qualifiedSpecClassName.lastIndexOf('.') + 1)
      + componentClassName;
 }
 return ClassName.bestGuess(qualifiedComponentClassName);
}

代码示例来源:origin: JakeWharton/butterknife

private static TypeName bestGuess(String type) {
 switch (type) {
  case "void": return TypeName.VOID;
  case "boolean": return TypeName.BOOLEAN;
  case "byte": return TypeName.BYTE;
  case "char": return TypeName.CHAR;
  case "double": return TypeName.DOUBLE;
  case "float": return TypeName.FLOAT;
  case "int": return TypeName.INT;
  case "long": return TypeName.LONG;
  case "short": return TypeName.SHORT;
  default:
   int left = type.indexOf('<');
   if (left != -1) {
    ClassName typeClassName = ClassName.bestGuess(type.substring(0, left));
    List<TypeName> typeArguments = new ArrayList<>();
    do {
     typeArguments.add(WildcardTypeName.subtypeOf(Object.class));
     left = type.indexOf('<', left + 1);
    } while (left != -1);
    return ParameterizedTypeName.get(typeClassName,
      typeArguments.toArray(new TypeName[typeArguments.size()]));
   }
   return ClassName.bestGuess(type);
 }
}

代码示例来源:origin: square/dagger

@Override public TypeName visitError(ErrorType errorType, Void v) {
 // Error type found, a type may not yet have been generated, but we need the type
 // so we can generate the correct code in anticipation of the type being available
 // to the compiler.
 // Paramterized types which don't exist are returned as an error type whose name is "<any>"
 if ("<any>".equals(errorType.toString())) {
  throw new CodeGenerationIncompleteException(
    "Type reported as <any> is likely a not-yet generated parameterized type.");
 }
 return ClassName.bestGuess(errorType.toString());
}

代码示例来源:origin: facebook/litho

private static TagModel newTagModel(Element typeElement, Types types) {
  return new TagModel(
    ClassName.bestGuess(typeElement.toString()),
    types.directSupertypes(typeElement.asType()).size()
      > 1, // java.lang.Object is always a supertype
    !typeElement.getEnclosedElements().isEmpty(),
    typeElement);
 }
}

代码示例来源:origin: facebook/litho

/**
  * There are a few cases of classes with typeArgs (e.g. {@literal MyClass<SomeClass, ..>}) where
  *
  * <p>TypeName.get() throws an error like: "com.sun.tools.javac.code.Symbol$CompletionFailure:
  * class file for SomeClass not found". Therefore we manually get the qualified name and create
  * the TypeName from the path String.
  */
 private static TypeName safelyGetTypeName(TypeMirror t) {
  TypeName typeName;
  try {
   typeName = TypeName.get(t);
  } catch (Exception e) {
   final String qualifiedName;
   if (t instanceof DeclaredType) {
    qualifiedName =
      ((TypeElement) ((DeclaredType) t).asElement()).getQualifiedName().toString();
   } else {
    String tmp = t.toString();
    qualifiedName = tmp.substring(0, tmp.indexOf('<'));
   }

   typeName = ClassName.bestGuess(qualifiedName);
  }

  return typeName;
 }
}

代码示例来源:origin: bluelinelabs/LoganSquare

public TypeName getParameterizedParentTypeName() {
  if (parentUsedTypeParameters.size() > 0) {
    List<TypeName> usedParameters = new ArrayList<>();
    for (String parameter : parentUsedTypeParameters) {
      if (parameter.indexOf(".") > 0) {
        usedParameters.add(ClassName.bestGuess(parameter));
      } else {
        usedParameters.add(TypeVariableName.get(parameter));
      }
    }
    return ParameterizedTypeName.get((ClassName)parentTypeName, usedParameters.toArray(new TypeName[usedParameters.size()]));
  } else {
    return parentTypeName;
  }
}

代码示例来源:origin: facebook/litho

private static TypeName getEnclosedImplClassName(final SpecModel enclosedSpecModel) {
 final String componentTypeName = enclosedSpecModel.getComponentTypeName().toString();
 if (enclosedSpecModel.getTypeVariables().isEmpty()) {
  return ClassName.bestGuess(componentTypeName);
 }
 final TypeName[] typeNames =
   enclosedSpecModel
     .getTypeVariables()
     .stream()
     .map(TypeVariableName::withoutAnnotations)
     .collect(Collectors.toList())
     .toArray(new TypeName[] {});
 return ParameterizedTypeName.get(ClassName.bestGuess(componentTypeName), typeNames);
}

代码示例来源:origin: square/wire

public @Nullable TypeName getTarget(ProtoType type) {
 TypeConfigElement typeConfig = typeConfig(type);
 return typeConfig != null ? ClassName.bestGuess(typeConfig.target()) : null;
}

代码示例来源:origin: facebook/litho

private static List<AnnotationSpec> getExternalAnnotations(VariableElement param) {
 final List<? extends AnnotationMirror> annotationMirrors = param.getAnnotationMirrors();
 final List<AnnotationSpec> annotations = new ArrayList<>();
 for (AnnotationMirror annotationMirror : annotationMirrors) {
  if (annotationMirror.getAnnotationType().toString().startsWith(COMPONENTS_PACKAGE)) {
   continue;
  }
  final AnnotationSpec.Builder annotationSpec =
    AnnotationSpec.builder(
      ClassName.bestGuess(annotationMirror.getAnnotationType().toString()));
  Map<? extends ExecutableElement, ? extends AnnotationValue> elementValues =
    annotationMirror.getElementValues();
  for (Map.Entry<? extends ExecutableElement, ? extends AnnotationValue> elementValue :
    elementValues.entrySet()) {
   annotationSpec.addMember(
     elementValue.getKey().getSimpleName().toString(),
     elementValue.getValue().toString());
  }
  annotations.add(annotationSpec.build());
 }
 return annotations;
}

代码示例来源:origin: facebook/litho

private static MethodSpec generateRecordRenderDataMethod(SpecModel specModel) {
 final TypeName renderInfoTypeName = ClassName.bestGuess(getRenderDataImplClassName(specModel));
 final CodeBlock code =
   CodeBlock.builder()
     .add("$T $L = $L != null ?\n", renderInfoTypeName, "renderInfo", "toRecycle")
     .indent()
     .add("($T) $L :\n", renderInfoTypeName, "toRecycle")
     .add("new $T();\n", renderInfoTypeName)
     .unindent()
     .addStatement("$L.record(this)", "renderInfo")
     .addStatement("return $L", "renderInfo")
     .build();
 return MethodSpec.methodBuilder("recordRenderData")
   .addAnnotation(Override.class)
   .addModifiers(Modifier.PROTECTED)
   .addParameter(ClassNames.RENDER_DATA, "toRecycle")
   .returns(ClassNames.RENDER_DATA)
   .addCode(code)
   .build();
}

代码示例来源:origin: Graylog2/graylog2-server

@Nonnull
private String functionArgsHolder(FunctionDescriptor<?> function) {
  // create the argument holder for the function invocation (and create the holder class if it doesn't exist yet)
  final String functionArgsClassname = functionArgsHolderClass(function);
  final String functionArgsMember = functionReference(function) + "$" + subExpressionName();
  classFile.addField(FieldSpec.builder(
      ClassName.bestGuess(functionArgsClassname), functionArgsMember, Modifier.PRIVATE)
      .build());
  lateConstructorBlock.addStatement("$L = new $L()", functionArgsMember, functionArgsClassname);
  return functionArgsMember;
}

代码示例来源:origin: facebook/litho

if (hasState) {
 final ClassName stateContainerClass =
   ClassName.bestGuess(getStateContainerClassName(specModel));
 constructorBuilder.addStatement(
   STATE_CONTAINER_FIELD_NAME + " = new $T()", stateContainerClass);

代码示例来源:origin: facebook/litho

@Test
public void testNonEmptyTag() {
 TagModel nonEmptyInterface = mTagModels.get(1);
 assertThat(nonEmptyInterface.name)
   .isEqualTo(
     ClassName.bestGuess(
       "com.facebook.litho.specmodels.processor.TagExtractorTest.NonEmptyInterface"));
 assertThat(nonEmptyInterface.hasMethods).isTrue();
}

代码示例来源:origin: facebook/litho

@Test
 public void testTagWithExtend() {
  TagModel extendedInterface = mTagModels.get(2);
  assertThat(extendedInterface.name)
    .isEqualTo(
      ClassName.bestGuess(
        "com.facebook.litho.specmodels.processor.TagExtractorTest.ExtendedInterface"));
  assertThat(extendedInterface.hasSupertype).isTrue();
 }
}

代码示例来源:origin: facebook/litho

@Test
public void testValidExtraction() {
 TagModel emptyInterface = mTagModels.get(0);
 assertThat(emptyInterface.name)
   .isEqualTo(
     ClassName.bestGuess(
       "com.facebook.litho.specmodels.processor.TagExtractorTest.EmptyInterface"));
 assertThat(emptyInterface.hasMethods).isFalse();
 assertThat(emptyInterface.hasSupertype).isFalse();
}

代码示例来源:origin: facebook/litho

@Test
public void testGetTypeVariablesOnClassName() {
 TypeName objectClass = ClassName.bestGuess("java.lang.Object");
 assertThat(MethodParamModelUtils.getTypeVariables(objectClass)).isEmpty();
}

代码示例来源:origin: facebook/litho

@Test
public void testGetTypeVariablesOnParameterizedTypeRecursive() {
 TypeVariableName type1 = TypeVariableName.get("R");
 TypeVariableName type2 = TypeVariableName.get("S");
 TypeVariableName type3 = TypeVariableName.get("T");
 TypeName type =
   ParameterizedTypeName.get(
     ClassName.bestGuess("java.lang.Object"),
     type1,
     type2,
     ParameterizedTypeName.get(ClassName.bestGuess("java.lang.Object"), type3));
 assertThat(MethodParamModelUtils.getTypeVariables(type)).hasSize(3);
 assertThat(MethodParamModelUtils.getTypeVariables(type)).contains(type1);
 assertThat(MethodParamModelUtils.getTypeVariables(type)).contains(type2);
 assertThat(MethodParamModelUtils.getTypeVariables(type)).contains(type3);
}

代码示例来源:origin: facebook/litho

@Before
public void setup() {
 when(mLayoutSpecModel.getRepresentedObject()).thenReturn(mModelRepresentedObject);
 when(mMountSpecModel.getRepresentedObject()).thenReturn(mMountSpecObject);
 mOnCreateMountContent =
   SpecMethodModel.<DelegateMethod, Void>builder()
     .annotations(ImmutableList.of((Annotation) () -> OnCreateMountContent.class))
     .modifiers(ImmutableList.of(Modifier.STATIC))
     .name("onCreateMountContent")
     .returnTypeSpec(new TypeSpec(ClassName.bestGuess("java.lang.MadeUpClass")))
     .typeVariables(ImmutableList.of())
     .methodParams(
       ImmutableList.of(
         MockMethodParamModel.newBuilder()
           .name("c")
           .type(ClassNames.ANDROID_CONTEXT)
           .representedObject(new Object())
           .build()))
     .representedObject(mOnCreateMountContentObject)
     .typeModel(null)
     .build();
}

相关文章