@SuppressWarnings("unchecked") private Object toValue(Object bean, Field field, XMLNode node) throws Exception { Class<?> type = field.getType(); field.setAccessible(true); Object current = field.get(bean); if (current != null) type = current.getClass(); if (Collection.class.isAssignableFrom(type)) { Type eleParamType = Object.class; ParameterizedType paramType = (ParameterizedType) field.getGenericType(); if (paramType.getActualTypeArguments().length > 0) { eleParamType = paramType.getActualTypeArguments()[0]; } Object[] array = (Object[]) toArrayValues((Class<?>) eleParamType, node); Collection collection = null; if (current != null && current instanceof Collection) { collection = (Collection) current; } else if (type.isInterface()) { collection = new ArrayList<Object>(); } else { collection = (Collection) type.newInstance(); } Collections.addAll(collection, array); return collection; } if (type.isArray()) return toArrayValues(type, node); return toValue(type, node); }
/** * Determines the component type. Lists is the first type, Map is the second type, etc. * * @param type The parametrized type. * @param path The path to the type, used in exception message. * @return The component type. */ public static Type componentType(Type type, String path) { if (type instanceof ParameterizedType) { ParameterizedType parameterizedType = (ParameterizedType) type; Class<?> rawType = (Class<?>) parameterizedType.getRawType(); if (Map.class.isAssignableFrom(rawType)) { return parameterizedType.getActualTypeArguments()[1]; } else if (Collection.class.isAssignableFrom(rawType)) { return parameterizedType.getActualTypeArguments()[0]; } else { throw new CollectionExpressionException("Unknown collection type [" + type + "]"); } } else if (type instanceof GenericArrayType) { return ((GenericArrayType) type).getGenericComponentType(); } Class<?> rawType = (Class<?>) type; if (Map.class == type || Collection.class == type) { throw new CollectionExpressionException( "The method or member [" + path + "] returns a simple " + "Map or Collection. Unable to determine the type of the Map or Collection. " + "Please make this method generic so that the correct type can be determined."); } else if (rawType.isArray()) { return rawType.getComponentType(); } return rawType; }
private void writeObject( ContentValues values, Object object, String columnName, ParameterizedType fieldType) throws IOException { if (object == null) return; final Type rawType = fieldType.getRawType(); if (!(rawType instanceof Class)) throw new UnsupportedOperationException(); final Class rawCls = (Class) rawType; if (List.class.isAssignableFrom(rawCls)) { values.put( columnName, LoganSquare.serialize((List) object, (Class) fieldType.getActualTypeArguments()[0])); } else if (Map.class.isAssignableFrom(rawCls)) { //noinspection unchecked values.put( columnName, LoganSquare.serialize((Map) object, (Class) fieldType.getActualTypeArguments()[1])); } else if (rawCls.isArray()) { final Class componentType = rawCls.getComponentType(); values.put( columnName, LoganSquare.serialize((List) Arrays.asList((Object[]) object), componentType)); } else { values.put(columnName, LoganSquare.serialize(object)); } }
static Class<?> getTypeClass(Type type) { if (type instanceof Class<?>) { return (Class<?>) type; } if (type instanceof ParameterizedType) { ParameterizedType pt = (ParameterizedType) type; Class<?> c = (Class<?>) pt.getRawType(); if (ValuedEnum.class.isAssignableFrom(c)) { Type[] types = pt.getActualTypeArguments(); if (types == null || types.length != 1) { c = int.class; } else { c = getTypeClass(pt.getActualTypeArguments()[0]); } } return c; } if (type instanceof GenericArrayType) { if (Object.class.isAssignableFrom( getTypeClass(((GenericArrayType) type).getGenericComponentType()))) { return Object[].class; } } throw new UnsupportedOperationException("Unknown type type : " + type.getClass().getName()); }
@Override public <T> ParamConverter<T> getConverter( final Class<T> rawType, final Type genericType, final Annotation[] annotations) { if (rawType != List.class) return null; if (genericType instanceof ParameterizedType) { final ParameterizedType parameterizedType = (ParameterizedType) genericType; if (parameterizedType.getActualTypeArguments().length != 1) return null; if (parameterizedType.getActualTypeArguments()[0] != String.class) return null; } else { return null; } return (ParamConverter<T>) new ParamConverter<List<String>>() { @Override public List<String> fromString(final String value) { return Arrays.asList(value.split(",")); } @Override public String toString(final List<String> value) throws IllegalArgumentException { return value.toString(); } }; }
/** * Get the class instance of a specific generic index in the baseclass passed to this method. * * @param baseClass is the class to read from * @param genericIdx is the index of the generic parameter's class we want * @return the generic class */ public static Class<?> getGenericClassAtIndexForEvent(Class<?> baseClass, int genericIdx) { if (baseClass == null) { throw new IllegalArgumentException("Base class cannot be null"); } if (genericIdx < 0) { throw new IllegalArgumentException("The generic index cannot be smaller than zero"); } // get to the level at which this class is defined as an EventHandler ParameterizedType eventHandlerType = getEventHandlerClass(baseClass); if (eventHandlerType == null) { throw new IllegalStateException( "Could not find event handler class for this base class, not an EventHandler."); } // make sure we can actually retrieve the index we need if (eventHandlerType.getActualTypeArguments().length <= genericIdx) { throw new IllegalArgumentException("Index cannot be retrieved, type does not have enough"); } // get the correct generic instance, drill up a level when it's a parameterized type (generic in // generic) Type genInstance = eventHandlerType.getActualTypeArguments()[genericIdx]; if (genInstance instanceof ParameterizedType) { genInstance = ((ParameterizedType) genInstance).getRawType(); } // return its class return (Class<?>) genInstance; }
/** Returns true if {@code a} and {@code b} are equal. */ public static boolean equals(Type a, Type b) { if (a == b) { // also handles (a == null && b == null) return true; } else if (a instanceof Class) { // Class already specifies equals(). return a.equals(b); } else if (a instanceof ParameterizedType) { if (!(b instanceof ParameterizedType)) { return false; } // TODO: save a .clone() call ParameterizedType pa = (ParameterizedType) a; ParameterizedType pb = (ParameterizedType) b; return equal(pa.getOwnerType(), pb.getOwnerType()) && pa.getRawType().equals(pb.getRawType()) && Arrays.equals(pa.getActualTypeArguments(), pb.getActualTypeArguments()); } else if (a instanceof GenericArrayType) { if (!(b instanceof GenericArrayType)) { return false; } GenericArrayType ga = (GenericArrayType) a; GenericArrayType gb = (GenericArrayType) b; return equals(ga.getGenericComponentType(), gb.getGenericComponentType()); } else if (a instanceof WildcardType) { if (!(b instanceof WildcardType)) { return false; } WildcardType wa = (WildcardType) a; WildcardType wb = (WildcardType) b; return Arrays.equals(wa.getUpperBounds(), wb.getUpperBounds()) && Arrays.equals(wa.getLowerBounds(), wb.getLowerBounds()); } else if (a instanceof TypeVariable) { if (!(b instanceof TypeVariable)) { return false; } TypeVariable<?> va = (TypeVariable<?>) a; TypeVariable<?> vb = (TypeVariable<?>) b; return va.getGenericDeclaration() == vb.getGenericDeclaration() && va.getName().equals(vb.getName()); } else { // This isn't a type we support. Could be a generic array type, // wildcard type, etc. return false; } }
@Test public void testURIDeclarations() throws NoSuchMethodException, SecurityException { Assert.assertNotNull(A.class.getMethod("addA", Object.class)); Assert.assertNotNull(B.class.getMethod("addA", Object.class)); Method uriMethod = B.class.getMethod("getA"); Assert.assertTrue(uriMethod.getGenericReturnType() instanceof ParameterizedType); ParameterizedType returnType = (ParameterizedType) uriMethod.getGenericReturnType(); Assert.assertEquals(returnType.getActualTypeArguments().length, 1); Assert.assertTrue(returnType.getActualTypeArguments()[0] instanceof WildcardType); Assert.assertEquals( ((WildcardType) returnType.getActualTypeArguments()[0]).getUpperBounds()[0], URI.class); }
/* * Enabled force condition propagation * Lifted jumps to return sites */ private static boolean typeEquals(ParameterizedType arrtype, ParameterizedType arrtype2, Map<String, Type> map) { if (!arrtype.getRawType().equals(arrtype2.getRawType())) return false; arrtype = arrtype.getActualTypeArguments(); arrtype2 = arrtype2.getActualTypeArguments(); int n2 = 0; while (n2 < arrtype.length) { if (!TypeToken.matches(arrtype[n2], arrtype2[n2], map)) { return false; } ++n2; } return true; }
/** * Analyze a complex parametrized type attribute (which can be a list or map for example) * * @param parameterizedType * @param rawType */ protected void analyzeParametrizedType(ParameterizedType parameterizedType, Type rawType) { if (List.class.equals(rawType)) { this.isList = true; if (parameterizedType.getActualTypeArguments()[0] instanceof Class && ((Class) parameterizedType.getActualTypeArguments()[0]) .isAnnotationPresent(DTO.class)) { isListOfDto = true; dtoImpl = convertType(parameterizedType.getActualTypeArguments()[0]) + "Impl"; } } else if (Map.class.equals(rawType)) { isMap = true; } }
private Object generate(Class<?> type, boolean alternative) { for (Generator<?> generator : generators) { ParameterizedType generic = (ParameterizedType) generator.getClass().getGenericInterfaces()[0]; Class<?> restrained = generic.getActualTypeArguments()[0] instanceof ParameterizedType ? (Class<?>) ((ParameterizedType) generic.getActualTypeArguments()[0]).getRawType() : (Class<?>) generic.getActualTypeArguments()[0]; if (type.isAssignableFrom(restrained)) { type = generator.generate(); } } return type == String.class ? alternative ? OTHER_STRING : DEFAULT_STRING : mock(type); }
@SuppressWarnings("unchecked") private void apply(Object mock) { for (Refinement refinement : refinements) { ParameterizedType generic = (ParameterizedType) refinement.getClass().getGenericInterfaces()[0]; Class<?> restrained = generic.getActualTypeArguments()[0] instanceof ParameterizedType ? (Class<?>) ((ParameterizedType) generic.getActualTypeArguments()[0]).getRawType() : (Class<?>) generic.getActualTypeArguments()[0]; if (restrained.isInstance(mock)) { refinement.apply(mock); } } }
private Object replace(Class<?> type, ApplicableGenerator generator, boolean alternative) { for (Creator<?> creator : creators) { ParameterizedType generic = (ParameterizedType) creator.getClass().getGenericInterfaces()[0]; Class<?> restrained = generic.getActualTypeArguments()[0] instanceof ParameterizedType ? (Class<?>) ((ParameterizedType) generic.getActualTypeArguments()[0]).getRawType() : (Class<?>) generic.getActualTypeArguments()[0]; if (type.isAssignableFrom(restrained)) { return creator.create(); } } return generator.generate(type, alternative); }
/** * Checks if two parameterized types are exactly equal, under the variable replacement described * in the typeVarMap. */ private static boolean typeEquals( ParameterizedType from, ParameterizedType to, Map<String, Type> typeVarMap) { if (from.getRawType().equals(to.getRawType())) { Type[] fromArgs = from.getActualTypeArguments(); Type[] toArgs = to.getActualTypeArguments(); for (int i = 0; i < fromArgs.length; i++) { if (!matches(fromArgs[i], toArgs[i], typeVarMap)) { return false; } } return true; } return false; }
@Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { Preference annotation = method.getAnnotation(Preference.class); String key = annotation.value(); String defaultString = annotation.defaultString(); boolean defaultBoolean = annotation.defaultBoolean(); int defaultInt = annotation.defaultInt(); long defaultLong = annotation.defaultLong(); float defaultFloat = annotation.defaultFloat(); if (method.getReturnType().equals(StringEntry.class)) { return new StringEntry(preferences, key, defaultString); } else if (method.getReturnType().equals(FloatEntry.class)) { return new FloatEntry(preferences, key, defaultFloat); } else if (method.getReturnType().equals(LongEntry.class)) { return new LongEntry(preferences, key, defaultLong); } else if (method.getReturnType().equals(IntEntry.class)) { return new IntEntry(preferences, key, defaultInt); } else if (method.getReturnType().equals(BooleanEntry.class)) { return new BooleanEntry(preferences, key, defaultBoolean); } else if (method.getReturnType().equals(ObjectEntry.class)) { if (method.getGenericReturnType() instanceof ParameterizedType) { ParameterizedType parameterizedType = (ParameterizedType) method.getGenericReturnType(); Class<?> type = (Class) parameterizedType.getActualTypeArguments()[0]; return new ObjectEntry<>(preferences, key, gson, type); } throw new RuntimeException("ObjectEntries must have a parameter"); } else { return null; } }
/** * Gets the specific Pojo class. * * @return the specific Pojo class */ protected Class getDomainClass() { if (domainClass == null) { ParameterizedType thisType = (ParameterizedType) getClass().getGenericSuperclass(); domainClass = (Class) thisType.getActualTypeArguments()[0]; } return domainClass; }
/** * Returns the component types of the given type. Returns <code>null</code> if given type does not * have a single component type. For example the following types all have the component-type * MyClass: * * <ul> * <li>MyClass[] * <li>List<MyClass> * <li>Foo<? extends MyClass> * <li>Bar<? super MyClass> * <li><T extends MyClass> T[] * </ul> */ public static Class[] getComponentTypes(Type type, Class implClass) { if (type instanceof Class) { Class clazz = (Class) type; if (clazz.isArray()) { return new Class[] {clazz.getComponentType()}; } } else if (type instanceof ParameterizedType) { ParameterizedType pt = (ParameterizedType) type; Type[] generics = pt.getActualTypeArguments(); if (generics.length == 0) { return null; } Class[] types = new Class[generics.length]; for (int i = 0; i < generics.length; i++) { types[i] = getRawType(generics[i], implClass); } return types; } else if (type instanceof GenericArrayType) { GenericArrayType gat = (GenericArrayType) type; Class rawType = getRawType(gat.getGenericComponentType(), implClass); if (rawType == null) { return null; } return new Class[] {rawType}; } return null; }
/** * Creates the type, it's private so you must use fromType. * * @param type */ private JavaType(Type type) { // the type this.type = type; // parameterized? parameterizedType = ParameterizedType.class.isInstance(type) ? ParameterizedType.class.cast(type) : null; // generic info genericInfo = parameterizedType != null; // get class if (Class.class.isInstance(type)) { clazz = Class.class.cast(type); } else if (parameterizedType != null) { clazz = Class.class.cast(parameterizedType.getRawType()); } else { clazz = null; } // component type if (clazz != null && clazz.getComponentType() != null) { componentType = clazz.getComponentType(); } // instantiable instantiable = clazz != null; // typeParameters typeParameters = parameterizedType != null ? parameterizedType.getActualTypeArguments() : null; // genericInfo genericInfo = typeParameters != null; }
// 反射获取T的simpleName public BaseService() { Type type = this.getClass().getGenericSuperclass(); ParameterizedType pt = (ParameterizedType) type; Type[] types = pt.getActualTypeArguments(); clazz = (Class<T>) types[0]; Tname = clazz.getSimpleName(); }
/** * Infer value type in one collection type * * @param genericType * @return */ public static Type inferElementTypeIn(Type collectionType) { if (collectionType instanceof Class) { return Object.class; } else if (collectionType instanceof ParameterizedType) { ParameterizedType parameterizedCollectionType = (ParameterizedType) collectionType; Type collectionValueType = parameterizedCollectionType.getActualTypeArguments()[0]; if (collectionValueType instanceof Class) { return (Class) collectionValueType; } else if (collectionValueType instanceof ParameterizedType) { ParameterizedType type = (ParameterizedType) collectionValueType; return type.getRawType(); } else if (collectionValueType instanceof WildcardType) { throw new UnusableTypeException( "we can't infer element type in widlcard type " + collectionType.toString()); } else if (collectionValueType instanceof TypeVariable) { throw new UnusableTypeException( "we can't infer element type in type variable " + collectionType.toString()); } } else if (collectionType instanceof WildcardType) { throw new UnusableTypeException( "we can't infer element type in widlcard type " + collectionType.toString()); } else if (collectionType instanceof TypeVariable) { throw new UnusableTypeException( "we can't infer element type in type variable " + collectionType.toString()); } throw new UnusableTypeException("we can't infer element type in " + collectionType.toString()); }
/** * 返回一个type的泛型数组, 如果没有, 则直接返回null * * @param type * @return */ public static Type[] getGenericsTypes(Type type) { if (type instanceof ParameterizedType) { ParameterizedType pt = (ParameterizedType) type; return pt.getActualTypeArguments(); } return null; }
private String nameFor(ParameterizedType type) { Class<?> raw = (Class<?>) type.getRawType(); if (Collection.class.isAssignableFrom(raw)) { return nameFor(type.getActualTypeArguments()[0]) + "List"; } return nameFor(raw); }
public static Class getFieldGenericType(Field field) { if (ParameterizedType.class.isAssignableFrom(field.getGenericType().getClass())) { ParameterizedType genericType = (ParameterizedType) field.getGenericType(); return (Class) genericType.getActualTypeArguments()[0]; } return Void.class; }
@SuppressWarnings("unchecked") static Class<? extends Event<?>> getEventClass(Class<?> handlerClass) { for (Class<?> i : handlerClass.getInterfaces()) { if (EventHandler.class.equals(i)) { for (Type t : handlerClass.getGenericInterfaces()) { if (t instanceof ParameterizedType) { ParameterizedType pt = (ParameterizedType) t; if (EventHandler.class.equals(pt.getRawType())) { return (Class<? extends Event<?>>) pt.getActualTypeArguments()[0]; } } } } else if (EventHandler.class.isAssignableFrom(i)) { return getEventClass((Class<? extends EventHandler<?>>) i); } } if (EventHandler.class.isAssignableFrom(handlerClass.getSuperclass())) { return getEventClass((Class<?>) handlerClass.getSuperclass()); } return null; }
private static void checkFacadeInjectionPoint(InjectionPoint injectionPoint, Class<?> type) { if (injectionPoint.getAnnotated().getBaseType().equals(type)) { if (injectionPoint.getType() instanceof ParameterizedType) { ParameterizedType parameterizedType = (ParameterizedType) injectionPoint.getType(); if (parameterizedType.getActualTypeArguments()[0] instanceof TypeVariable<?>) { throw new DefinitionException(INJECTION_POINT_WITH_TYPE_VARIABLE, injectionPoint); } if (parameterizedType.getActualTypeArguments()[0] instanceof WildcardType) { throw new DefinitionException(INJECTION_POINT_HAS_WILDCARD, type, injectionPoint); } } else { throw new DefinitionException( INJECTION_POINT_MUST_HAVE_TYPE_PARAMETER, type, injectionPoint); } } }
public void testResolveToGenericArrayType() { GenericArrayType arrayType = (GenericArrayType) new Holder<List<int[][]>[]>() {}.getContentType(); ParameterizedType listType = (ParameterizedType) arrayType.getGenericComponentType(); assertEquals(List.class, listType.getRawType()); assertEquals(Types.newArrayType(int[].class), listType.getActualTypeArguments()[0]); }
@Override protected void found(final Class<ActEventListener> target, final App app) { final EventBus bus = app.eventBus(); ParameterizedType ptype = null; Type superType = target.getGenericSuperclass(); while (ptype == null) { if (superType instanceof ParameterizedType) { ptype = (ParameterizedType) superType; } else { if (Object.class == superType) { logger.warn("Event listener registration failed: cannot find generic information for %s", target.getName()); return; } superType = ((Class) superType).getGenericSuperclass(); } } Type[] ca = ptype.getActualTypeArguments(); for (Type t : ca) { if (t instanceof Class) { final Class tc = (Class) t; if (ActEvent.class.isAssignableFrom(tc)) { app.eventBus().bind(AppEventId.DEPENDENCY_INJECTOR_LOADED, new AppEventListenerBase() { @Override public void on(EventObject event) throws Exception { ActEventListener listener = (ActEventListener) app.newInstance(target); bus.bind(tc, listener); } }); return; } } } }
@Nullable private static TypeWrapper wrap(Type type) { if (type == null) { return null; } else if (type instanceof Class) { return new ClassTypeWrapper((Class<?>) type); } else if (type instanceof ParameterizedType) { ParameterizedType parameterizedType = (ParameterizedType) type; return new ParameterizedTypeWrapper( toWrappers(parameterizedType.getActualTypeArguments()), (ClassTypeWrapper) wrap(parameterizedType.getRawType()), wrap(parameterizedType.getOwnerType())); } else if (type instanceof WildcardType) { WildcardType wildcardType = (WildcardType) type; return new WildcardTypeWrapper( toWrappers(wildcardType.getUpperBounds()), toWrappers(wildcardType.getLowerBounds()), type.hashCode()); } else if (type instanceof TypeVariable) { TypeVariable<?> typeVariable = (TypeVariable<?>) type; return new TypeVariableTypeWrapper( typeVariable.getName(), toWrappers(typeVariable.getBounds()), type.hashCode()); } else if (type instanceof GenericArrayType) { GenericArrayType genericArrayType = (GenericArrayType) type; return new GenericArrayTypeWrapper( wrap(genericArrayType.getGenericComponentType()), type.hashCode()); } else { throw new IllegalArgumentException("cannot wrap type of type " + type.getClass()); } }
@Override public void map( ServiceReference<ModelAdapterBuilder> serviceReference, Emitter<String> emitter) { Registry registry = RegistryUtil.getRegistry(); ModelAdapterBuilder modelAdapterBuilder = registry.getService(serviceReference); Type genericInterface = ReflectionUtil.getGenericInterface( modelAdapterBuilder, ModelAdapterBuilder.class); if ((genericInterface == null) || !(genericInterface instanceof ParameterizedType)) { return; } ParameterizedType parameterizedType = (ParameterizedType) genericInterface; Type[] typeArguments = parameterizedType.getActualTypeArguments(); if (ArrayUtil.isEmpty(typeArguments) || (typeArguments.length != 2)) { return; } try { Class adapteeModelClass = (Class) typeArguments[0]; Class adaptedModelClass = (Class) typeArguments[1]; emitter.emit(getKey(adapteeModelClass, adaptedModelClass)); } catch (ClassCastException cce) { return; } }
private static Class getClass(ParameterizedType paramParameterizedType) { paramParameterizedType = paramParameterizedType.getActualTypeArguments(); if (paramParameterizedType.length > 0) { return getClass(paramParameterizedType[0]); } return null; }