Java Code Examples for java.lang.reflect.Type#toString()

The following examples show how to use java.lang.reflect.Type#toString() . 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 File: ExceptionDiagnosisTest.java    From openjdk-8-source with GNU General Public License v2.0 6 votes vote down vote up
private static void checkExceptionChain(
        String what, Throwable e, Type[] expectedTypes) {
    System.out.println("Exceptions in chain for " + what + ":");
    for (Throwable t = e; t != null; t = t.getCause())
        System.out.println(".." + t);

    String messageChain = messageChain(e);

    // Now check that each of the classes is mentioned in those messages
    for (Type type : expectedTypes) {
        String name = (type instanceof Class) ?
            ((Class<?>) type).getName() : type.toString();
        if (!messageChain.contains(name)) {
            fail("Exception chain for " + what + " does not mention " +
                    name);
            System.out.println("Full stack trace:");
            e.printStackTrace(System.out);
        }
    }

    System.out.println();
}
 
Example 2
Source File: ToStringBuilder.java    From javers with Apache License 2.0 6 votes vote down vote up
public static String typeName(Type type){
    if (type instanceof ParameterizedType) {
        ParameterizedType parameterizedType = (ParameterizedType)type;
        parameterizedType.getActualTypeArguments();

        StringBuilder out = new StringBuilder();
        out.append(typeName(parameterizedType.getRawType()) + "<");
        Type[] args  = ((ParameterizedType)type).getActualTypeArguments();

        out.append( typeName(args[0]));
        for (int i=1;i<args.length;i++){
            out.append(", "+typeName(args[i]) );
        }
        out.append(">");
        return out.toString();
    } else if (type instanceof Class) {
        return ((Class)type).getSimpleName();
    } else {
        return type.toString();
    }
}
 
Example 3
Source File: ExceptionDiagnosisTest.java    From dragonwell8_jdk with GNU General Public License v2.0 6 votes vote down vote up
private static void checkExceptionChain(
        String what, Throwable e, Type[] expectedTypes) {
    System.out.println("Exceptions in chain for " + what + ":");
    for (Throwable t = e; t != null; t = t.getCause())
        System.out.println(".." + t);

    String messageChain = messageChain(e);

    // Now check that each of the classes is mentioned in those messages
    for (Type type : expectedTypes) {
        String name = (type instanceof Class) ?
            ((Class<?>) type).getName() : type.toString();
        if (!messageChain.contains(name)) {
            fail("Exception chain for " + what + " does not mention " +
                    name);
            System.out.println("Full stack trace:");
            e.printStackTrace(System.out);
        }
    }

    System.out.println();
}
 
Example 4
Source File: L.java    From Android-utils with Apache License 2.0 6 votes vote down vote up
static <T> Class getTypeClassFromParadigm(final IFormatter<T> formatter) {
    Type[] genericInterfaces = formatter.getClass().getGenericInterfaces();
    Type type;
    if (genericInterfaces.length == 1) {
        type = genericInterfaces[0];
    } else {
        type = formatter.getClass().getGenericSuperclass();
    }
    type = ((ParameterizedType) type).getActualTypeArguments()[0];
    while (type instanceof ParameterizedType) {
        type = ((ParameterizedType) type).getRawType();
    }
    String className = type.toString();
    if (className.startsWith("class ")) {
        className = className.substring(6);
    } else if (className.startsWith("interface ")) {
        className = className.substring(10);
    }
    try {
        return Class.forName(className);
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    }
    return null;
}
 
Example 5
Source File: ExceptionDiagnosisTest.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
private static void checkExceptionChain(
        String what, Throwable e, Type[] expectedTypes) {
    System.out.println("Exceptions in chain for " + what + ":");
    for (Throwable t = e; t != null; t = t.getCause())
        System.out.println(".." + t);

    String messageChain = messageChain(e);

    // Now check that each of the classes is mentioned in those messages
    for (Type type : expectedTypes) {
        String name = (type instanceof Class) ?
            ((Class<?>) type).getName() : type.toString();
        if (!messageChain.contains(name)) {
            fail("Exception chain for " + what + " does not mention " +
                    name);
            System.out.println("Full stack trace:");
            e.printStackTrace(System.out);
        }
    }

    System.out.println();
}
 
Example 6
Source File: Logs.java    From tomee with Apache License 2.0 6 votes vote down vote up
public static String name(final Type type) {
    if (type instanceof Class<?>) {
        return ((Class) type).getSimpleName().replace("java.lang.", "").replace("java.util", "");
    } else if (type instanceof ParameterizedType) {
        final ParameterizedType pt = (ParameterizedType) type;
        final StringBuilder builder = new StringBuilder();
        builder.append(name(pt.getRawType()));
        final Type[] args = pt.getActualTypeArguments();
        if (args != null) {
            builder.append("<");
            for (int i = 0; i < args.length; i++) {
                builder.append(name(args[i]));
                if (i < args.length - 1) {
                    builder.append(", ");
                }
            }
            builder.append(">");
        }
        return builder.toString();
    }
    return type.toString();
}
 
Example 7
Source File: ModuleInfo.java    From SugarOnRest with MIT License 5 votes vote down vote up
/**
 *  Gets class name (module name) from Java class type.
 *
 * @param type The Java type.
 * @return Class name.
 */
public static String getClassName(Type type) {
    if (type == null) {
        return StringUtils.EMPTY;
    }
    String typeToString =  type.toString();
    typeToString = typeToString.trim();
    String[] splitArray = typeToString.split("\\.");
    if (splitArray.length > 0) {
        return splitArray[splitArray.length - 1];
    }

    return StringUtils.EMPTY;
}
 
Example 8
Source File: SpecimenType.java    From jfixture with MIT License 5 votes vote down vote up
private static String justClassName(Type type) {
    if(type instanceof SpecimenType) return type.toString();
    if(!(type instanceof Class)) throw new RuntimeException("This shouldn't happen");

    Class clazz =(Class)type;
    return clazz.getName();
}
 
Example 9
Source File: MapTypeBuilder.java    From saluki with Apache License 2.0 5 votes vote down vote up
@Override
public TypeDefinition build(Type type, Class<?> clazz, Map<Class<?>, TypeDefinition> typeCache) {
    if (!(type instanceof ParameterizedType)) {
        throw new IllegalArgumentException(MessageFormat.format("[Jaket] Unexpected type {0}.",
                new Object[]{type}));
    }

    ParameterizedType parameterizedType = (ParameterizedType) type;
    Type[] actualTypeArgs = parameterizedType.getActualTypeArguments();
    if (actualTypeArgs == null || actualTypeArgs.length != 2) {
        throw new IllegalArgumentException(MessageFormat.format(
                "[Jaket] Map type [{0}] with unexpected amount of arguments [{1}]." + actualTypeArgs, new Object[] {
                        type, actualTypeArgs }));
    }

    for (Type actualType : actualTypeArgs) {
        if (actualType instanceof ParameterizedType) {
            // Nested collection or map.
            Class<?> rawType = (Class<?>) ((ParameterizedType) actualType).getRawType();
            JaketTypeBuilder.build(actualType, rawType, typeCache);
        } else if (actualType instanceof Class<?>) {
            Class<?> actualClass = (Class<?>) actualType;
            if (actualClass.isArray() || actualClass.isEnum()) {
                JaketTypeBuilder.build(null, actualClass, typeCache);
            } else {
                DefaultTypeBuilder.build(actualClass, typeCache);
            }
        }
    }

    TypeDefinition td = new TypeDefinition(type.toString());
    return td;
}
 
Example 10
Source File: SArray.java    From ethdroid with MIT License 5 votes vote down vote up
public static Class<? extends SType> getNestedType(Type type) {
    if (type instanceof ParameterizedType) {
        return SArray.getNestedType(((ParameterizedType) type).getActualTypeArguments()[0]);
    } else if (type instanceof Class) {
        return (Class<? extends SType>) type;
    } else {
        throw new EthDroidException("type not handled (" + type.toString() + ")");
    }
}
 
Example 11
Source File: TypeToken.java    From firebase-android-sdk with Apache License 2.0 5 votes vote down vote up
@NonNull
private static <T> TypeToken<T> of(@NonNull Type type) {
  if (type instanceof WildcardType) {
    if (((WildcardType) type).getLowerBounds().length == 0) {
      return of(((WildcardType) type).getUpperBounds()[0]);
    }
    throw new IllegalArgumentException("<? super T> is not supported");
  } else if (type instanceof GenericArrayType) {
    Type componentType = ((GenericArrayType) type).getGenericComponentType();
    return new ArrayToken<T>(TypeToken.of(componentType));
  } else if (type instanceof ParameterizedType) {
    ParameterizedType parameterizedType = (ParameterizedType) type;
    // Safe because rawType of parameterizedType is always instance of Class<T>
    @SuppressWarnings("unchecked")
    Class<T> rawType = (Class<T>) parameterizedType.getRawType();
    Type[] types = parameterizedType.getActualTypeArguments();
    TypeToken[] typeTokens = new TypeToken[types.length];
    for (int i = 0; i < types.length; i++) {
      typeTokens[i] = TypeToken.of(types[i]);
    }
    return new ClassToken<T>(rawType, new TypeTokenContainer(typeTokens));
  } else if (type instanceof Class<?>) {
    // Safe because type is instance of Class<?>
    @SuppressWarnings("unchecked")
    Class<T> typeToken = (Class<T>) type;
    if (typeToken.isArray()) {
      Class<?> componentTypeToken = typeToken.getComponentType();
      // Safe because typeToken is an Array and componentTypeToken will never be null
      @SuppressWarnings("ConstantConditions")
      ArrayToken<T> arrayToken = new ArrayToken<T>(TypeToken.of(componentTypeToken));
      return arrayToken;
    }
    return new ClassToken<T>(typeToken);
  } else {
    throw new IllegalArgumentException("Type: " + type.toString() + " not supported.");
  }
}
 
Example 12
Source File: AbstractJpaDataObjectProvider.java    From katharsis-framework with Apache License 2.0 5 votes vote down vote up
private Class<?> getElementType(Type type) {
	if (type instanceof Class) {
		return (Class<?>) type;
	} else if (type instanceof ParameterizedType) {
		ParameterizedType paramType = (ParameterizedType) type;
		if (paramType.getRawType() instanceof Class && Map.class.isAssignableFrom((Class<?>) paramType.getRawType())) {
			return getElementType(paramType.getActualTypeArguments()[1]);
		}
		if (paramType.getRawType() instanceof Class && Collection.class.isAssignableFrom((Class<?>) paramType.getRawType())) {
			return getElementType(paramType.getActualTypeArguments()[0]);
		}
	}
	throw new IllegalArgumentException(type.toString());
}
 
Example 13
Source File: JsonUtils.java    From kurento-java with Apache License 2.0 5 votes vote down vote up
private static String getTypeName(Type type) {

    if (type instanceof Class) {

      Class<?> clazz = (Class<?>) type;
      return clazz.getSimpleName();

    } else if (type instanceof ParameterizedType) {

      StringBuilder sb = new StringBuilder();

      ParameterizedType pType = (ParameterizedType) type;
      Class<?> rawClass = (Class<?>) pType.getRawType();

      sb.append(rawClass.getSimpleName());

      Type[] arguments = pType.getActualTypeArguments();
      if (arguments.length > 0) {
        sb.append('<');
        for (Type aType : arguments) {
          sb.append(getTypeName(aType));
          sb.append(',');
        }
        sb.deleteCharAt(sb.length() - 1);
        sb.append('>');
      }

      return sb.toString();
    }

    return type.toString();
  }
 
Example 14
Source File: TypeUtils.java    From BaseProject with Apache License 2.0 4 votes vote down vote up
public static String typeToString(Type type) {
    return type instanceof Class ? ((Class<?>) type).getName() : type.toString();
}
 
Example 15
Source File: Types.java    From android-discourse with Apache License 2.0 4 votes vote down vote up
public static String typeToString(Type type) {
    return type instanceof Class ? ((Class<?>) type).getName() : type.toString();
}
 
Example 16
Source File: MoreTypes.java    From soabase-halva with Apache License 2.0 4 votes vote down vote up
public static String typeToString(Type type) {
  return type instanceof Class ? ((Class) type).getName() : type.toString();
}
 
Example 17
Source File: b.java    From letv with Apache License 2.0 4 votes vote down vote up
public static String c(Type type) {
    return type instanceof Class ? ((Class) type).getName() : type.toString();
}
 
Example 18
Source File: ConstructorConstructor.java    From GVGAI_GYM with Apache License 2.0 4 votes vote down vote up
/**
 * Constructors for common interface types like Map and List and their
 * subtypes.
 */
@SuppressWarnings("unchecked") // use runtime checks to guarantee that 'T' is what it is
private <T> ObjectConstructor<T> newDefaultImplementationConstructor(
    final Type type, Class<? super T> rawType) {
  if (Collection.class.isAssignableFrom(rawType)) {
    if (SortedSet.class.isAssignableFrom(rawType)) {
      return new ObjectConstructor<T>() {
        @Override public T construct() {
          return (T) new TreeSet<Object>();
        }
      };
    } else if (EnumSet.class.isAssignableFrom(rawType)) {
      return new ObjectConstructor<T>() {
        @SuppressWarnings("rawtypes")
        @Override public T construct() {
          if (type instanceof ParameterizedType) {
            Type elementType = ((ParameterizedType) type).getActualTypeArguments()[0];
            if (elementType instanceof Class) {
              return (T) EnumSet.noneOf((Class)elementType);
            } else {
              throw new JsonIOException("Invalid EnumSet type: " + type.toString());
            }
          } else {
            throw new JsonIOException("Invalid EnumSet type: " + type.toString());
          }
        }
      };
    } else if (Set.class.isAssignableFrom(rawType)) {
      return new ObjectConstructor<T>() {
        @Override public T construct() {
          return (T) new LinkedHashSet<Object>();
        }
      };
    } else if (Queue.class.isAssignableFrom(rawType)) {
      return new ObjectConstructor<T>() {
        @Override public T construct() {
          return (T) new ArrayDeque<Object>();
        }
      };
    } else {
      return new ObjectConstructor<T>() {
        @Override public T construct() {
          return (T) new ArrayList<Object>();
        }
      };
    }
  }

  if (Map.class.isAssignableFrom(rawType)) {
    if (ConcurrentNavigableMap.class.isAssignableFrom(rawType)) {
      return new ObjectConstructor<T>() {
        @Override public T construct() {
          return (T) new ConcurrentSkipListMap<Object, Object>();
        }
      };
    } else if (ConcurrentMap.class.isAssignableFrom(rawType)) {
      return new ObjectConstructor<T>() {
        @Override public T construct() {
          return (T) new ConcurrentHashMap<Object, Object>();
        }
      };
    } else if (SortedMap.class.isAssignableFrom(rawType)) {
      return new ObjectConstructor<T>() {
        @Override public T construct() {
          return (T) new TreeMap<Object, Object>();
        }
      };
    } else if (type instanceof ParameterizedType && !(String.class.isAssignableFrom(
        TypeToken.get(((ParameterizedType) type).getActualTypeArguments()[0]).getRawType()))) {
      return new ObjectConstructor<T>() {
        @Override public T construct() {
          return (T) new LinkedHashMap<Object, Object>();
        }
      };
    } else {
      return new ObjectConstructor<T>() {
        @Override public T construct() {
          return (T) new LinkedTreeMap<String, Object>();
        }
      };
    }
  }

  return null;
}
 
Example 19
Source File: $Gson$Types.java    From gson with Apache License 2.0 4 votes vote down vote up
public static String typeToString(Type type) {
  return type instanceof Class ? ((Class<?>) type).getName() : type.toString();
}
 
Example 20
Source File: Types.java    From codebuff with BSD 2-Clause "Simplified" License votes vote down vote up
/**
 * Returns human readable string representation of {@code type}.
 * <ul>
 * <li>For array type {@code Foo[]}, {@code "com.mypackage.Foo[]"} are returned.
 * <li>For any class, {@code theClass.getName()} are returned.
 * <li>For all other types, {@code type.toString()} are returned.
 * </ul>
 */


static String toString(Type type) {
  return (type instanceof Class) ? ((Class<?>) type).getName() : type.toString();
}