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

The following examples show how to use java.lang.reflect.Type#getClass() . 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: ClassUtils.java    From DevUtils with Apache License 2.0 6 votes vote down vote up
/**
 * 获取 Type Class
 * @param type {@link Type}
 * @return Type Class
 */
public static Class<?> getClass(final Type type) {
    if (type == null) return null;
    try {
        if (type.getClass() == Class.class) {
            return (Class<?>) type;
        }
        if (type instanceof ParameterizedType) {
            return getClass(((ParameterizedType) type).getRawType());
        }
        if (type instanceof TypeVariable) {
            Type boundType = ((TypeVariable<?>) type).getBounds()[0];
            return (Class<?>) boundType;
        }
        if (type instanceof WildcardType) {
            Type[] upperBounds = ((WildcardType) type).getUpperBounds();
            if (upperBounds.length == 1) {
                return getClass(upperBounds[0]);
            }
        }
    } catch (Exception e) {
        JCLogUtils.eTag(TAG, e, "getClass");
    }
    return Object.class;
}
 
Example 2
Source File: ClassUtils.java    From DevUtils with Apache License 2.0 6 votes vote down vote up
/**
 * 获取 Type Class
 * @param type {@link Type}
 * @return Type Class
 */
public static Class<?> getClass(final Type type) {
    if (type == null) return null;
    try {
        if (type.getClass() == Class.class) {
            return (Class<?>) type;
        }
        if (type instanceof ParameterizedType) {
            return getClass(((ParameterizedType) type).getRawType());
        }
        if (type instanceof TypeVariable) {
            Type boundType = ((TypeVariable<?>) type).getBounds()[0];
            return (Class<?>) boundType;
        }
        if (type instanceof WildcardType) {
            Type[] upperBounds = ((WildcardType) type).getUpperBounds();
            if (upperBounds.length == 1) {
                return getClass(upperBounds[0]);
            }
        }
    } catch (Exception e) {
        JCLogUtils.eTag(TAG, e, "getClass");
    }
    return Object.class;
}
 
Example 3
Source File: InjectorUtils.java    From AuthMeReloaded with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Returns the given type as a {@link Class}.
 *
 * @param type the type to convert
 * @return class corresponding to the provided type
 */
public static Class<?> convertToClass(Type type) {
    if (type instanceof Class<?>) {
        return (Class<?>) type;
    } else if (type instanceof ParameterizedType) {
        Type rawType = ((ParameterizedType) type).getRawType();
        if (rawType instanceof Class<?>) {
            return (Class<?>) rawType;
        } else {
            throw new IllegalStateException("Got raw type '" + rawType + "' of type '"
                + rawType.getClass() + "' for genericType '" + type + "'");
        }
    }
    Class<?> typeClass = type == null ? null : type.getClass();
    throw new IllegalStateException("Unknown type implementation '" + typeClass + "' for '" + type + "'");
}
 
Example 4
Source File: GeciReflectionTools.java    From javageci with Apache License 2.0 6 votes vote down vote up
/**
 * Get the generic type name of the type passed as argument. The JDK
 * {@code Type#getTypeName()} returns a string that contains the
 * classes with their names and not with the canonical names (inner
 * classes have {@code $} in the names instead of dot). This method
 * goes through the type structure and converts the names (generic
 * types also) to
 *
 * @param t the type
 * @return the type as string
 */
public static String getGenericTypeName(Type t) {
    final String normalizedName;
    if (t instanceof ParameterizedType) {
        normalizedName = getGenericParametrizedTypeName((ParameterizedType) t);
    } else if (t instanceof Class<?>) {
        normalizedName = removeJavaLang(((Class) t).getCanonicalName());
    } else if (t instanceof WildcardType) {
        normalizedName = getGenericWildcardTypeName((WildcardType) t);
    } else if (t instanceof GenericArrayType) {
        var at = (GenericArrayType) t;
        normalizedName = getGenericTypeName(at.getGenericComponentType()) + "[]";
    } else if (t instanceof TypeVariable) {
        normalizedName = t.getTypeName();
    } else {
        throw new GeciException(
            "Type is something not handled. It is '%s' for the type '%s'",
            t.getClass(), t.getTypeName());
    }
    return normalizedName;
}
 
Example 5
Source File: Types.java    From ProjectAres with GNU Affero General Public License v3.0 6 votes vote down vote up
public static boolean isFullySpecified(Type type) {
    checkNotNull(type);
    if(type instanceof Class) {
        return true;
    } else if(type instanceof TypeVariable) {
        return false;
    } else if(type instanceof GenericArrayType) {
        return isFullySpecified(((GenericArrayType) type).getGenericComponentType());
    } else if(type instanceof WildcardType) {
        final WildcardType wildcard = (WildcardType) type;
        return Stream.of(wildcard.getLowerBounds()).allMatch(Types::isFullySpecified) &&
               Stream.of(wildcard.getUpperBounds()).allMatch(Types::isFullySpecified);
    } else if(type instanceof ParameterizedType) {
        final ParameterizedType parameterized = (ParameterizedType) type;
        return isFullySpecified(parameterized.getRawType()) &&
               (parameterized.getOwnerType() == null || isFullySpecified(parameterized.getOwnerType())) &&
               Stream.of(parameterized.getActualTypeArguments()).allMatch(Types::isFullySpecified);
    } else {
        throw new IllegalArgumentException("Unhandled metatype " + type.getClass());
    }
}
 
Example 6
Source File: CollectionCoercer.java    From selenium with Apache License 2.0 6 votes vote down vote up
@Override
public BiFunction<JsonInput, PropertySetting, T> apply(Type type) {
  Type valueType;

  if (type instanceof ParameterizedType) {
    ParameterizedType pt = (ParameterizedType) type;
    valueType = pt.getActualTypeArguments()[0];
  } else if (type instanceof Class) {
    valueType = Object.class;
  } else {
    throw new IllegalArgumentException("Unhandled type: " + type.getClass());
  }

  return (jsonInput, setting) -> {
    jsonInput.beginArray();
    T toReturn = new JsonInputIterator(jsonInput).asStream()
        .map(in -> coercer.coerce(in, valueType, setting))
        .collect(collector);
    jsonInput.endArray();

    return toReturn;
  };
}
 
Example 7
Source File: ReflectionEncryptionEventListener.java    From spring-data-mongodb-encrypt with Apache License 2.0 6 votes vote down vote up
static void diveInto(Function<Object, Object> crypt, List value, Type fieldType) {
    if (fieldType instanceof ParameterizedType) {
        ParameterizedType subType = (ParameterizedType) fieldType;
        Class rawType = (Class) subType.getRawType();

        if (Collection.class.isAssignableFrom(rawType)) {
            Type subFieldType = subType.getActualTypeArguments()[0];

            for (Object o : value)
                diveIntoGeneric(crypt, o, subFieldType);

        } else {
            throw new IllegalArgumentException("Unknown reflective raw type class " + rawType.getClass() + "; should be Map<> or Collection<>");
        }
    } else {
        throw new IllegalArgumentException("Unknown reflective type class " + fieldType.getClass());
    }
}
 
Example 8
Source File: TypeLiteral.java    From java with MIT License 6 votes vote down vote up
private static String formatTypeWithoutSpecialCharacter(Type type) {
    if (type instanceof Class) {
        Class clazz = (Class) type;
        return clazz.getCanonicalName();
    }
    if (type instanceof ParameterizedType) {
        ParameterizedType pType = (ParameterizedType) type;
        String typeName = formatTypeWithoutSpecialCharacter(pType.getRawType());
        for (Type typeArg : pType.getActualTypeArguments()) {
            typeName += "_";
            typeName += formatTypeWithoutSpecialCharacter(typeArg);
        }
        return typeName;
    }
    if (type instanceof GenericArrayType) {
        GenericArrayType gaType = (GenericArrayType) type;
        return formatTypeWithoutSpecialCharacter(gaType.getGenericComponentType()) + "_array";
    }
    if (type instanceof WildcardType) {
        return Object.class.getCanonicalName();
    }
    throw new JsonException("unsupported type: " + type + ", of class " + type.getClass());
}
 
Example 9
Source File: BaseTypeFactory.java    From baratine with GNU General Public License v2.0 6 votes vote down vote up
public BaseType createForSource(Type type)
{
  if (type instanceof BaseType) {
    return (BaseType) type;
  }
  
  BaseType baseType = _sourceCache.get(type);

  if (baseType == null) {
    baseType = BaseType.createForSource(type,
                                        new HashMap<String,BaseType>(),
                                        null);

    if (baseType == null)
      throw new NullPointerException("unsupported BaseType: " + type + " " + type.getClass());

    _sourceCache.put(type, baseType);
  }

  return baseType;
}
 
Example 10
Source File: BaseTypeFactory.java    From baratine with GNU General Public License v2.0 6 votes vote down vote up
public BaseType createForTarget(Type type)
{
  if (type instanceof BaseType)
    return (BaseType) type;
  
  BaseType baseType = _targetCache.get(type);

  if (baseType == null) {
    baseType = BaseType.createForTarget(type,
                                        new HashMap<String,BaseType>(),
                                        null);

    if (baseType == null)
      throw new NullPointerException("unsupported BaseType: " + type + " " + type.getClass());

    _targetCache.put(type, baseType);
  }

  return baseType;
}
 
Example 11
Source File: Java8.java    From groovy with Apache License 2.0 6 votes vote down vote up
private ClassNode configureType(Type type) {
    if (type instanceof WildcardType) {
        return configureWildcardType((WildcardType) type);
    } else if (type instanceof ParameterizedType) {
        return configureParameterizedType((ParameterizedType) type);
    } else if (type instanceof GenericArrayType) {
        return configureGenericArray((GenericArrayType) type);
    } else if (type instanceof TypeVariable) {
        return configureTypeVariableReference(((TypeVariable) type).getName());
    } else if (type instanceof Class) {
        return configureClass((Class<?>) type);
    } else if (type==null) {
        throw new GroovyBugError("Type is null. Most probably you let a transform reuse existing ClassNodes with generics information, that is now used in a wrong context.");
    } else {
        throw new GroovyBugError("unknown type: " + type + " := " + type.getClass());
    }
}
 
Example 12
Source File: ModelRegistryBackedModelRules.java    From pushfish-android with BSD 2-Clause "Simplified" License 5 votes vote down vote up
private <T> Class<T> getActionObjectType(Action<T> action) {
    Class<? extends Action> aClass = action.getClass();
    Type[] genericInterfaces = aClass.getGenericInterfaces();
    Type actionType = findFirst(genericInterfaces, new Spec<Type>() {
        public boolean isSatisfiedBy(Type element) {
            return element instanceof ParameterizedType && ((ParameterizedType) element).getRawType().equals(Action.class);
        }
    });

    final Class<?> modelType;

    if (actionType == null) {
        modelType = Object.class;
    } else {
        ParameterizedType actionParamaterizedType = (ParameterizedType) actionType;
        Type tType = actionParamaterizedType.getActualTypeArguments()[0];

        if (tType instanceof Class) {
            modelType = (Class) tType;
        } else if (tType instanceof ParameterizedType) {
            modelType = (Class) ((ParameterizedType) tType).getRawType();
        } else if (tType instanceof TypeVariable) {
            TypeVariable  typeVariable = (TypeVariable) tType;
            Type[] bounds = typeVariable.getBounds();
            return (Class<T>) bounds[0];
        } else {
            throw new RuntimeException("Don't know how to handle type: " + tType.getClass());
        }
    }

    @SuppressWarnings("unchecked") Class<T> castModelType = (Class<T>) modelType;
    return castModelType;
}
 
Example 13
Source File: MapCoercer.java    From selenium with Apache License 2.0 5 votes vote down vote up
@Override
public BiFunction<JsonInput, PropertySetting, T> apply(Type type) {
  Type keyType;
  Type valueType;

  if (type instanceof ParameterizedType) {
    ParameterizedType pt = (ParameterizedType) type;
    keyType = pt.getActualTypeArguments()[0];
    valueType = pt.getActualTypeArguments()[1];
  } else if (type instanceof Class) {
    keyType = Object.class;
    valueType = Object.class;
  } else {
    throw new IllegalArgumentException("Unhandled type: " + type.getClass());
  }

  return (jsonInput, setting) -> {
    jsonInput.beginObject();
    T toReturn = new JsonInputIterator(jsonInput).asStream()
        .map(in -> {
               Object key = coercer.coerce(in, keyType, setting);
               Object value = coercer.coerce(in, valueType, setting);

               return new AbstractMap.SimpleImmutableEntry<>(key, value);
        })
        .collect(collector);
    jsonInput.endObject();

    return toReturn;
  };
}
 
Example 14
Source File: TypeMirrors.java    From FreeBuilder with Apache License 2.0 5 votes vote down vote up
/** Returns a {@link TypeMirror} for the given type. */
public static TypeMirror typeMirror(Types typeUtils, Elements elementUtils, Type type) {
  if (type instanceof Class) {
    return typeMirror(typeUtils, elementUtils, (Class<?>) type);
  } else if (type instanceof GenericArrayType) {
    Type componentType = ((GenericArrayType) type).getGenericComponentType();
    return typeUtils.getArrayType(typeMirror(typeUtils, elementUtils, componentType));
  } else if (type instanceof ParameterizedType) {
    ParameterizedType pType = (ParameterizedType) type;
    DeclaredType rawType = (DeclaredType) typeMirror(typeUtils, elementUtils, pType.getRawType());
    List<TypeMirror> typeArgumentMirrors = new ArrayList<>();
    for (Type typeArgument : pType.getActualTypeArguments()) {
      typeArgumentMirrors.add(typeMirror(typeUtils, elementUtils, typeArgument));
    }
    DeclaredType owner = (DeclaredType) typeMirror(typeUtils, elementUtils, pType.getOwnerType());
    return typeUtils.getDeclaredType(
        owner,
        (TypeElement) rawType.asElement(),
        typeArgumentMirrors.toArray(new TypeMirror[typeArgumentMirrors.size()]));
  } else if (type instanceof WildcardType) {
    Type lowerBound = getOnlyType(((WildcardType) type).getLowerBounds());
    Type upperBound = getOnlyType(((WildcardType) type).getUpperBounds());
    if (Object.class.equals(upperBound)) {
      upperBound = null;
    }
    return typeUtils.getWildcardType(
        typeMirror(typeUtils, elementUtils, upperBound),
        typeMirror(typeUtils, elementUtils, lowerBound));
  } else if (type == null) {
    return null;
  } else if (type instanceof TypeVariable) {
    throw new IllegalArgumentException("Type variables not supported");
  } else {
    throw new IllegalArgumentException("Unrecognized Type subclass " + type.getClass());
  }
}
 
Example 15
Source File: Types.java    From selenium with Apache License 2.0 5 votes vote down vote up
static Class<?> narrow(Type type) {
  if (type instanceof Class) {
    return (Class<?>) type;
  }

  if (type instanceof ParameterizedType) {
    return narrow(((ParameterizedType) type).getRawType());
  }

  throw new JsonException("Unable to narrow " + type.getClass());
}
 
Example 16
Source File: ClassUtil.java    From qaf with MIT License 5 votes vote down vote up
public static Class<?> getClass(Type typeOfT) {
	if (typeOfT instanceof ParameterizedType) {
		return getClass(((ParameterizedType) typeOfT).getRawType());
	}
	if (typeOfT instanceof Class) {
		return (Class<?>) typeOfT;
	}
	try {
		return ClassUtils.getClass(typeOfT.getTypeName());
	} catch (ClassNotFoundException e) {
		return typeOfT.getClass();
	}

}
 
Example 17
Source File: TypeUtils.java    From BigApp_Discuz_Android with Apache License 2.0 5 votes vote down vote up
public static Class<?> getClass(Type type) {
    if (type.getClass() == Class.class) {
        return (Class<?>) type;
    }

    if (type instanceof ParameterizedType) {
        return getClass(((ParameterizedType) type).getRawType());
    }

    return Object.class;
}
 
Example 18
Source File: ReflectionEncryptionEventListener.java    From spring-data-mongodb-encrypt with Apache License 2.0 5 votes vote down vote up
static void diveInto(Function<Object, Object> crypt, Document value, Type fieldType) {
    Class<?> childNode = fetchClassFromField(value);
    if (childNode != null) {
        cryptFields(value, childNode, crypt);
        return;
    }

    // fall back to reflection
    if (fieldType instanceof Class) {
        childNode = (Class) fieldType;
        cryptFields(value, childNode, crypt);
    } else {
        throw new IllegalArgumentException("Unknown reflective type class " + fieldType.getClass());
    }
}
 
Example 19
Source File: TypeInfo.java    From smallrye-graphql with Apache License 2.0 5 votes vote down vote up
private Class<?> raw(Type type) {
    if (type instanceof Class)
        return (Class<?>) type;
    if (type instanceof ParameterizedType)
        return raw(((ParameterizedType) type).getRawType());
    if (type instanceof TypeVariable)
        return resolveTypeVariable();
    throw new GraphQlClientException("unsupported reflection type " + type.getClass());
}
 
Example 20
Source File: SpecimenType.java    From jfixture with MIT License 4 votes vote down vote up
private static SpecimenType<?> of(Type type, GenericTypeCollection genericTypeArguments) {
    return new SpecimenType<Object>(type.getClass(), genericTypeArguments){};
}