com.google.common.reflect.TypeToken类的使用及代码示例

x33g5p2x  于2022-01-29 转载在 其他  
字(11.9k)|赞(0)|评价(0)|浏览(1055)

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

TypeToken介绍

[英]A Type with generics.

Operations that are otherwise only available in Class are implemented to support Type, for example #isSubtypeOf, #isArray and #getComponentType. It also provides additional utilities such as #getTypes, #resolveType, etc.

There are three ways to get a TypeToken instance:

  • Wrap a Type obtained via reflection. For example: TypeToken.of(method.getGenericReturnType()).
  • Capture a generic type with a (usually anonymous) subclass. For example:
new TypeToken>() {} 
}

Note that it's critical that the actual type argument is carried by a subclass. The following code is wrong because it only captures the type variable of the listType() method signature; while is lost in erasure:

class Util return new TypeToken>() {}; 
} 
} 
TypeToken> stringListType = Util.listType(); 
}
  • Capture a generic type with a (usually anonymous) subclass and resolve it against a context class that knows what the type parameters are. For example:
abstract class IKnowMyType TypeToken type = new TypeToken(getClass()) {}; 
} 
new IKnowMyType() {}.type => String 
}

TypeToken is serializable when no type variable is contained in the type.

Note to Guice users: TypeToken is similar to Guice's TypeLiteral class except that it is serializable and offers numerous additional utility methods.
[中]带有泛型的类型。
其他情况下仅在类中可用的操作被实现为支持类型,例如#isSubtypeOf、#isArray和#getComponentType。它还提供额外的实用程序,如#getTypes、#resolveType等。
获取TypeToken实例有三种方法:
*包裹通过反射获得的类型。例如:TypeToken。of(method.getGenericReturnType())。
*用(通常是匿名的)子类捕获泛型类型。例如:

new TypeToken>() {} 
}

请注意,实际的类型参数由子类携带是至关重要的。以下代码是错误的,因为它只捕获listType()方法签名的类型变量;当你迷失在擦除中:

class Util return new TypeToken>() {}; 
} 
} 
TypeToken> stringListType = Util.listType(); 
}

*用一个(通常是匿名的)子类捕获泛型类型,并根据一个知道类型参数的上下文类解析它。例如:

abstract class IKnowMyType TypeToken type = new TypeToken(getClass()) {}; 
} 
new IKnowMyType() {}.type => String 
}

当类型中不包含类型变量时,TypeToken是可序列化的。
Guice用户注意:TypeToken与Guice的TypeLiteral类类似,只是它是可序列化的,并提供了许多额外的实用方法。

代码示例

代码示例来源:origin: google/guava

public void testInstanceMethod_exceptionTypes() throws Exception {
 Invokable<?, ?> delegate = Prepender.method("prepend", Iterable.class);
 assertEquals(
   ImmutableList.of(
     TypeToken.of(IllegalArgumentException.class), TypeToken.of(NullPointerException.class)),
   delegate.getExceptionTypes());
}

代码示例来源:origin: google/guava

private ImmutableList<TypeToken<? super T>> boundsAsInterfaces(Type[] bounds) {
 ImmutableList.Builder<TypeToken<? super T>> builder = ImmutableList.builder();
 for (Type bound : bounds) {
  @SuppressWarnings("unchecked") // upper bound of T
  TypeToken<? super T> boundType = (TypeToken<? super T>) of(bound);
  if (boundType.getRawType().isInterface()) {
   builder.add(boundType);
  }
 }
 return builder.build();
}

代码示例来源:origin: google/guava

Type getTargetType(String methodName) throws Exception {
  ParameterizedType parameterType =
    (ParameterizedType)
      WithGenericBound.class.getDeclaredMethod(methodName, List.class)
        .getGenericParameterTypes()[0];
  parameterType =
    (ParameterizedType) TypeToken.of(this.getClass()).resolveType(parameterType).getType();
  return parameterType.getActualTypeArguments()[0];
 }
}

代码示例来源:origin: google/guava

private boolean isOwnedBySubtypeOf(Type supertype) {
 for (TypeToken<?> type : getTypes()) {
  Type ownerType = type.getOwnerTypeIfPresent();
  if (ownerType != null && of(ownerType).isSubtypeOf(supertype)) {
   return true;
  }
 }
 return false;
}

代码示例来源:origin: google/guava

@SuppressWarnings("RedundantTypeArguments")
 @Override
 public ImmutableSet<Class<?>> load(Class<?> concreteClass) {
  return ImmutableSet.<Class<?>>copyOf(
    TypeToken.of(concreteClass).getTypes().rawTypes());
 }
});

代码示例来源:origin: org.apache.brooklyn/brooklyn-utils-common

/** returns raw type, if it's raw, else null;
 * used e.g. to set only one of the raw type or the type token,
 * for instance to make serialized output nicer */
@Nullable
public static <T> Class<? super T> getRawTypeIfRaw(@Nullable TypeToken<T> type) {
  if (type==null || !type.equals(TypeToken.of(type.getRawType()))) {
    return null;
  } else {
    return type.getRawType();
  }
}

代码示例来源:origin: com.google.guava/guava-jdk5

@Nullable private TypeToken<? super T> boundAsSuperclass(Type bound) {
 TypeToken<?> token = of(bound);
 if (token.getRawType().isInterface()) {
  return null;
 }
 @SuppressWarnings("unchecked") // only upper bound of T is passed in.
 TypeToken<? super T> superclass = (TypeToken<? super T>) token;
 return superclass;
}

代码示例来源:origin: com.google.guava/guava-testlib-jdk5

private static Invokable<?, ?> invokable(@Nullable Object instance, Method method) {
 if (instance == null) {
  return Invokable.from(method);
 } else {
  return TypeToken.of(instance.getClass()).method(method);
 }
}

代码示例来源:origin: SpongePowered/SpongeAPI

@Nullable
public static Object mockParam(final Class<?> paramType, @Nullable final Class<?> target) {
  if (paramType == byte.class || paramType == Byte.class) {
    return (byte) 0;
    return Instant.now();
  } else if (paramType == TypeToken.class) {
    return TypeToken.of(Object.class);
  } else if (paramType == Color.class) {
    return Color.BLACK;

代码示例来源:origin: com.google.guava/guava-jdk5

@Override public boolean equals(@Nullable Object obj) {
 if (obj instanceof Element) {
  Element that = (Element) obj;
  return getOwnerType().equals(that.getOwnerType()) && member.equals(that.member);
 }
 return false;
}

代码示例来源:origin: google/guava

public void testMethod_declaredBySuperclass() throws Exception {
 Method toStringMethod = Object.class.getMethod("toString");
 ImmutableList<String> list = ImmutableList.of("foo");
 assertEquals(list.toString(), TypeToken.of(List.class).method(toStringMethod).invoke(list));
}

代码示例来源:origin: google/guava

public void testInnerClassWithAnnotatedConstructorParameter() {
 Constructor<?> constructor =
   InnerWithAnnotatedConstructorParameter.class.getDeclaredConstructors()[0];
 Invokable<?, ?> invokable = Invokable.from(constructor);
 assertEquals(1, invokable.getParameters().size());
 assertEquals(TypeToken.of(String.class), invokable.getParameters().get(0).getType());
}

代码示例来源:origin: google/guava

private static ImmutableList<Method> getAnnotatedMethodsNotCached(Class<?> clazz) {
 Set<? extends Class<?>> supertypes = TypeToken.of(clazz).getTypes().rawTypes();
 Map<MethodIdentifier, Method> identifiers = Maps.newHashMap();
 for (Class<?> supertype : supertypes) {
  for (Method method : supertype.getDeclaredMethods()) {
   if (method.isAnnotationPresent(Subscribe.class) && !method.isSynthetic()) {
    // TODO(cgdecker): Should check for a generic parameter type and error out
    Class<?>[] parameterTypes = method.getParameterTypes();
    checkArgument(
      parameterTypes.length == 1,
      "Method %s has @Subscribe annotation but has %s parameters."
        + "Subscriber methods must have exactly 1 parameter.",
      method,
      parameterTypes.length);
    MethodIdentifier ident = new MethodIdentifier(method);
    if (!identifiers.containsKey(ident)) {
     identifiers.put(ident, method);
    }
   }
  }
 }
 return ImmutableList.copyOf(identifiers.values());
}

代码示例来源:origin: google/guava

/**
 * Returns all declared parameters of this {@code Invokable}. Note that if this is a constructor
 * of a non-static inner class, unlike {@link Constructor#getParameterTypes}, the hidden {@code
 * this} parameter of the enclosing class is excluded from the returned parameters.
 */
public final ImmutableList<Parameter> getParameters() {
 Type[] parameterTypes = getGenericParameterTypes();
 Annotation[][] annotations = getParameterAnnotations();
 AnnotatedType[] annotatedTypes = getAnnotatedParameterTypes();
 ImmutableList.Builder<Parameter> builder = ImmutableList.builder();
 for (int i = 0; i < parameterTypes.length; i++) {
  builder.add(
    new Parameter(
      this, i, TypeToken.of(parameterTypes[i]), annotations[i], annotatedTypes[i]));
 }
 return builder.build();
}

代码示例来源:origin: google/guava

/** Returns all declared exception types of this {@code Invokable}. */
public final ImmutableList<TypeToken<? extends Throwable>> getExceptionTypes() {
 ImmutableList.Builder<TypeToken<? extends Throwable>> builder = ImmutableList.builder();
 for (Type type : getGenericExceptionTypes()) {
  // getGenericExceptionTypes() will never return a type that's not exception
  @SuppressWarnings("unchecked")
  TypeToken<? extends Throwable> exceptionType =
    (TypeToken<? extends Throwable>) TypeToken.of(type);
  builder.add(exceptionType);
 }
 return builder.build();
}

代码示例来源:origin: google/guava

/**
 * Returns the generic interfaces that this type directly {@code implements}. This method is
 * similar but different from {@link Class#getGenericInterfaces()}. For example, {@code new
 * TypeToken<List<String>>() {}.getGenericInterfaces()} will return a list that contains {@code
 * new TypeToken<Iterable<String>>() {}}; while {@code List.class.getGenericInterfaces()} will
 * return an array that contains {@code Iterable<T>}, where the {@code T} is the type variable
 * declared by interface {@code Iterable}.
 *
 * <p>If this type is a type variable or wildcard, its upper bounds are examined and those that
 * are either an interface or upper-bounded only by interfaces are returned. This means that the
 * returned types could include type variables too.
 */
final ImmutableList<TypeToken<? super T>> getGenericInterfaces() {
 if (runtimeType instanceof TypeVariable) {
  return boundsAsInterfaces(((TypeVariable<?>) runtimeType).getBounds());
 }
 if (runtimeType instanceof WildcardType) {
  return boundsAsInterfaces(((WildcardType) runtimeType).getUpperBounds());
 }
 ImmutableList.Builder<TypeToken<? super T>> builder = ImmutableList.builder();
 for (Type interfaceType : getRawType().getGenericInterfaces()) {
  @SuppressWarnings("unchecked") // interface of T
  TypeToken<? super T> resolvedInterface =
    (TypeToken<? super T>) resolveSupertype(interfaceType);
  builder.add(resolvedInterface);
 }
 return builder.build();
}

代码示例来源:origin: google/guava

private ImmutableList<Invokable<?, ?>> getFactoriesToTest() {
  ImmutableList.Builder<Invokable<?, ?>> builder = ImmutableList.builder();
  for (Invokable<?, ?> factory : factories) {
   if (returnTypeToTest.isAssignableFrom(factory.getReturnType().getRawType())) {
    builder.add(factory);
   }
  }
  ImmutableList<Invokable<?, ?>> factoriesToTest = builder.build();
  Assert.assertFalse(
    "No "
      + factoryMethodsDescription
      + " that return "
      + returnTypeToTest.getName()
      + " or subtype are found in "
      + declaringClass
      + ".",
    factoriesToTest.isEmpty());
  return factoriesToTest;
 }
}

代码示例来源:origin: google/guava

private ImmutableList<Method> getVisibleMethods(Class<?> cls) {
  // Don't use cls.getPackage() because it does nasty things like reading
  // a file.
  String visiblePackage = Reflection.getPackageName(cls);
  ImmutableList.Builder<Method> builder = ImmutableList.builder();
  for (Class<?> type : TypeToken.of(cls).getTypes().rawTypes()) {
   if (!Reflection.getPackageName(type).equals(visiblePackage)) {
    break;
   }
   for (Method method : type.getDeclaredMethods()) {
    if (!method.isSynthetic() && isVisible(method)) {
     builder.add(method);
    }
   }
  }
  return builder.build();
 }
}

代码示例来源:origin: google/guava

public void testConstructor_parameters() throws Exception {
 Invokable<?, Prepender> delegate = Prepender.constructor(String.class, int.class);
 ImmutableList<Parameter> parameters = delegate.getParameters();
 assertEquals(2, parameters.size());
 assertEquals(String.class, parameters.get(0).getType().getType());
 assertTrue(parameters.get(0).isAnnotationPresent(NotBlank.class));
 assertEquals(int.class, parameters.get(1).getType().getType());
 assertFalse(parameters.get(1).isAnnotationPresent(NotBlank.class));
 new EqualsTester()
   .addEqualityGroup(parameters.get(0))
   .addEqualityGroup(parameters.get(1))
   .testEquals();
}

代码示例来源:origin: google/guava

private static <T> void callAllPublicMethods(TypeToken<T> type, T object)
   throws InvocationTargetException {
  for (Method method : type.getRawType().getMethods()) {
   if ((method.getModifiers() & STATIC) != 0) {
    continue;
   }
   ImmutableList<Parameter> parameters = type.method(method).getParameters();
   Object[] args = new Object[parameters.size()];
   for (int i = 0; i < parameters.size(); i++) {
    args[i] = getDefaultValue(parameters.get(i).getType());
   }
   try {
    try {
     method.invoke(object, args);
    } catch (InvocationTargetException ex) {
     try {
      throw ex.getCause();
     } catch (UnsupportedOperationException unsupported) {
      // this is a legit exception
     }
    }
   } catch (Throwable cause) {
    throw new InvocationTargetException(
      cause, method + " with args: " + Arrays.toString(args));
   }
  }
 }
}

相关文章

微信公众号

最新文章

更多

TypeToken类方法