List of usage examples for java.lang Class getTypeParameters
@SuppressWarnings("unchecked") public TypeVariable<Class<T>>[] getTypeParameters()
From source file:org.itest.impl.ITestRandomObjectGeneratorImpl.java
protected Object newInstance(Class<?> clazz, ITestContext iTestContext, Type... typeActualArguments) { Object res;/*w ww . j a v a 2s. com*/ Constructor<?> c = getConstructor(clazz); final Map<String, Type> map = new HashMap<String, Type>(); TypeVariable<?> typeArguments[] = clazz.getTypeParameters(); for (int i = 0; i < typeActualArguments.length; i++) { map.put(typeArguments[i].getName(), typeActualArguments[i]); } Type[] constructorTypes = c.getGenericParameterTypes(); Object[] constructorArgs = new Object[constructorTypes.length]; for (int i = 0; i < constructorTypes.length; i++) { Type pt = ITestTypeUtil.getTypeProxy(constructorTypes[i], map); iTestContext.enter(iTestContext.getCurrentOwner(), "<init[" + i + "]>"); iTestContext.setEmptyParam(); constructorArgs[i] = generateRandom(pt, Collections.EMPTY_MAP, iTestContext); iTestContext.leave(constructorArgs[i]); } try { res = c.newInstance(constructorArgs); } catch (Exception e) { // Object[] args = new Object[constructorArgs.length + 1]; // args[0] = generateRandom(clazz.getEnclosingClass(), null, null, owner, postProcess); // System.arraycopy(constructorArgs, 0, args, 1, constructorArgs.length); // try { // res = c.newInstance(args); // } catch (Exception ee) { // throw new RuntimeException(ee); // } throw new RuntimeException(e); } return res; }
From source file:org.kuali.rice.krad.uif.util.CopyUtils.java
/** * Get a field reference for temporary use while deep cloning. * /* ww w .j a v a 2 s . c om*/ * <p> * Call {@link #recycle(CopyReference)} when done working with the reference. * </p> * * @param source The source object. * @param target The target object. * @param field The field to use as the reference target. * * @return A field reference for temporary use while deep cloning. */ private static <T> FieldReference<T> getFieldReference(Object source, Object target, Field field, CopyReference<T> pref) { @SuppressWarnings("unchecked") FieldReference<T> ref = RecycleUtils.getRecycledInstance(FieldReference.class); if (ref == null) { ref = new FieldReference<T>(); } ref.source = source; ref.target = target; ref.field = field; DelayedCopy delayedCopy = field.getAnnotation(DelayedCopy.class); ref.delayAvailable = delayedCopy != null && (!delayedCopy.inherit() || pref.isDelayAvailable()); Map<String, Type> pTypeVars = pref.getTypeVariables(); if (pTypeVars != null && source != null) { Class<?> sourceType = source.getClass(); Class<?> targetClass = pref.getTargetClass(); Type targetType = ObjectPropertyUtils.findGenericType(sourceType, targetClass); if (targetType instanceof ParameterizedType) { ParameterizedType parameterizedTargetType = (ParameterizedType) targetType; Type[] params = parameterizedTargetType.getActualTypeArguments(); for (int j = 0; j < params.length; j++) { if (params[j] instanceof TypeVariable<?>) { Type pType = pTypeVars.get(targetClass.getTypeParameters()[j].getName()); ref.typeVariables.put(((TypeVariable<?>) params[j]).getName(), pType); } } } } Class<?> rawType = field.getType(); Type genericType = field.getGenericType(); if (genericType instanceof ParameterizedType) { ParameterizedType parameterizedType = (ParameterizedType) genericType; TypeVariable<?>[] typeParams = rawType.getTypeParameters(); Type[] params = parameterizedType.getActualTypeArguments(); assert params.length == typeParams.length; for (int i = 0; i < params.length; i++) { Type paramType = params[i]; if (paramType instanceof TypeVariable<?>) { Type fType = ref.typeVariables.get(((TypeVariable<?>) paramType).getName()); if (fType != null) { paramType = fType; } } ref.typeVariables.put(typeParams[i].getName(), paramType); } } return ref; }
From source file:org.openmainframe.ade.impl.PropertyAnnotation.java
/** * Find out what are the concrete classes used in an offspring class for the generic placeholders of a base class/interface * //from www . j a v a 2 s . c o m * @param <T> base class type * @param offspring class or interface subclassing or extending the base class * @param base class with generic arguments * @param actualArgs the actual type arguments passed to the offspring class (omit unless useful) * @return actual generic type arguments, must match the type parameters of the offspring class. If omitted, the * type parameters will be used instead. */ @SuppressWarnings("unchecked") public static <T> Type[] resolveActualTypeArgs(Class<? extends T> offspring, Class<T> base, Type... actualArgs) { // If actual types are omitted, the type parameters will be used instead. if (actualArgs.length == 0) { actualArgs = offspring.getTypeParameters(); } // map generic parameters into the actual types final Map<String, Type> genericVariables = new TreeMap<String, Type>(); for (int i = 0; i < actualArgs.length; i++) { final TypeVariable<?> typeVariable = (TypeVariable<?>) offspring.getTypeParameters()[i]; genericVariables.put(typeVariable.getName(), actualArgs[i]); } // Find direct ancestors (superclass, interfaces) final List<Type> ancestors = new LinkedList<Type>(); if (offspring.getGenericSuperclass() != null) { ancestors.add(offspring.getGenericSuperclass()); } for (Type t : offspring.getGenericInterfaces()) { ancestors.add(t); } // Recurse into ancestors (superclass, interfaces) for (Type type : ancestors) { if (type instanceof Class<?>) { // ancestor is non-parameterized. Recurse only if it matches the base class. final Class<?> ancestorClass = (Class<?>) type; if (base.isAssignableFrom(ancestorClass)) { final Type[] result = resolveActualTypeArgs((Class<? extends T>) ancestorClass, base); if (result != null) { return result; } } } if (type instanceof ParameterizedType) { // ancestor is parameterized. Recurse only if the raw type matches the base class. final ParameterizedType parameterizedType = (ParameterizedType) type; final Type rawType = parameterizedType.getRawType(); if (rawType instanceof Class<?>) { final Class<?> rawTypeClass = (Class<?>) rawType; if (base.isAssignableFrom(rawTypeClass)) { // loop through all type arguments and replace type variables with the actually known types final List<Type> resolvedTypes = new LinkedList<Type>(); for (Type t : parameterizedType.getActualTypeArguments()) { if (t instanceof TypeVariable<?>) { final Type resolvedType = genericVariables.get(((TypeVariable<?>) t).getName()); resolvedTypes.add(resolvedType != null ? resolvedType : t); } else if (t instanceof ParameterizedType) { final ParameterizedType pType = (ParameterizedType) t; final Type resolvedPType = new ResolvedParameterizedType(pType, genericVariables); resolvedTypes.add(resolvedPType); } else { resolvedTypes.add(t); } } final Type[] result = resolveActualTypeArgs((Class<? extends T>) rawTypeClass, base, resolvedTypes.toArray(new Type[] {})); if (result != null) { return result; } } } } } // we have a result if we reached the base class. return offspring.equals(base) ? actualArgs : null; }
From source file:org.rhq.core.pc.inventory.AutoDiscoveryExecutor.java
private boolean verifyComponentCompatibility(ResourceDiscoveryComponent component, ResourceComponent parentResourceComponent) throws PluginContainerException { Method discoveryCall = null;//from w w w .jav a2 s . co m try { discoveryCall = component.getClass().getMethod("discoverResources", ResourceCategory.class); } catch (NoSuchMethodException e) { throw new PluginContainerException("Resource component doesn't implement resource component interface", e); } Class<?> componentParameterType = discoveryCall.getParameterTypes()[0]; TypeVariable<? extends Class<?>>[] types = componentParameterType.getTypeParameters(); if (types.length == 0) { // The component doesn't declare type and therefore doesn't care what its parent type is return true; } TypeVariable<? extends Class<?>> type = types[0]; // TODO GH: Figure this out // if (type.getBounds()) // can we use: parentResourceComponent.getClass().isAssignableFrom( type.getGenericDeclaration().getClass() ) return true; }
From source file:org.shaman.rpg.editor.objects.ui.properties.AdvancedLogicSupport.java
private static String getVariableType(BaseModel model) { StringBuilder s = new StringBuilder(); Class<? extends BaseModel> mc = model.getClass(); s.append(mc.getCanonicalName());//from w w w . jav a2 s .c om if (mc.equals(ViewDelegateModel.class)) { //special case: view delegate model, use class of the view BaseView v = ((ViewDelegateModel) model).getView(); if (v != null) { Class<? extends BaseView> vc = v.getClass(); s.append("<? extends "); s.append(vc.getCanonicalName()); s.append(">"); return s.toString(); } } TypeVariable[] typeVars = mc.getTypeParameters(); if (typeVars.length > 0) { s.append("<"); for (int i = 0; i < typeVars.length; ++i) { if (i > 0) s.append(", "); resolveType(s, typeVars[i]); } s.append(">"); } return s.toString(); }
From source file:therian.Operation.java
/** * Learn whether {@code operator} seems to implement {@code this}. * * @param operator to check// w w w . ja v a 2 s .co m * @return boolean */ public boolean matches(Operator<?> operator) { final Type expectedType = TypeUtils.unrollVariables( TypeUtils.getTypeArguments(operator.getClass(), Operator.class), Operator.class.getTypeParameters()[0]); if (!TypeUtils.isInstance(this, expectedType)) { return false; } final Map<TypeVariable<?>, Type> typeArguments = TypeUtils.getTypeArguments(expectedType, Operation.class); for (Class<?> c : ClassUtils.hierarchy(TypeUtils.getRawType(expectedType, operator.getClass()))) { if (c.equals(Operation.class)) { break; } for (TypeVariable<?> var : c.getTypeParameters()) { Type type = Types.resolveAt(this, var, typeArguments); if (type == null || typeArguments == null) { continue; } if (type instanceof Class<?> && ((Class<?>) type).isPrimitive()) { type = ClassUtils.primitiveToWrapper((Class<?>) type); } if (!TypeUtils.isAssignable(type, TypeUtils.unrollVariables(typeArguments, var))) { return false; } } } return true; }
From source file:therian.operator.convert.AbstractConverter.java
/** * Learn whether a {@link Convert} operation's source value is (already) an instance of its target type, * * @param convert//from ww w . j a va 2 s.co m * @return boolean */ protected final boolean isNoop(Convert<?, ?> convert) { Type sourceType = convert.getSourcePosition().getType(); if (ParameterizedType.class.isInstance(sourceType) && convert.getSourcePosition().getValue() != null) { sourceType = Types.narrowestParameterizedType(convert.getSourcePosition().getValue().getClass(), (ParameterizedType) sourceType); } if (TypeUtils.isAssignable(sourceType, convert.getTargetPosition().getType())) { if (ParameterizedType.class.isInstance(convert.getTargetPosition().getType())) { // make sure all type params of target position are accounted for by source before declaring it a noop: final Class<?> rawTargetType = TypeUtils.getRawType(convert.getTargetPosition().getType(), null); final Map<TypeVariable<?>, Type> typeMappings = TypeUtils.getTypeArguments(sourceType, rawTargetType); for (TypeVariable<?> v : rawTargetType.getTypeParameters()) { if (typeMappings.get(v) == null) { return false; } if (typeMappings.get(v) instanceof TypeVariable<?>) { return false; } } } return true; } return false; }
From source file:uk.gov.gchq.koryphe.signature.Signature.java
/** * Create a <code>Signature</code> for the type variable at the given index. * * @param input Function to create signature for. * @param functionClass The input class * @param typeVariableIndex 0 for I or 1 for O. * @param isInput if true then it is an input signature otherwise it is an output signature * @return Signature of the type variable. *//* w ww. ja va 2 s . co m*/ private static Signature createSignatureFromTypeVariable(final Object input, final Class functionClass, final int typeVariableIndex, final boolean isInput) { TypeVariable<?> tv; if (input.getClass().getTypeParameters().length > typeVariableIndex) { tv = input.getClass().getTypeParameters()[typeVariableIndex]; } else { tv = functionClass.getTypeParameters()[typeVariableIndex]; } final Map<TypeVariable<?>, Type> typeArgs = TypeUtils.getTypeArguments(input.getClass(), functionClass); Type type = typeArgs.containsKey(tv) ? typeArgs.get(tv) : Object.class; return createSignature(input, type, typeArgs, isInput); }
From source file:weave.servlets.WeaveServlet.java
/** * Tries to convert value to the given type. * @param value The value to cast to a new type. * @param type The desired type./*from w w w.j a v a 2 s. c o m*/ * @return The value, which may have been cast as the new type. */ protected Object cast(Object value, Class<?> type) throws RemoteException { if (type.isInstance(value)) return value; try { if (value == null) // null -> NaN { if (type == double.class || type == Double.class) value = Double.NaN; else if (type == float.class || type == Float.class) value = Float.NaN; return value; } if (value instanceof Map) // Map -> Java Bean { Object bean = type.newInstance(); for (Field field : type.getFields()) { Object fieldValue = ((Map<?, ?>) value).get(field.getName()); fieldValue = cast(fieldValue, field.getType()); field.set(bean, fieldValue); } return bean; } if (type.isArray()) // ? -> T[] { if (value instanceof String) // String -> String[] value = CSVParser.defaultParser.parseCSVRow((String) value, true); if (value instanceof List) // List -> Object[] value = ((List<?>) value).toArray(); if (value.getClass().isArray()) // T1[] -> T2[] { int n = Array.getLength(value); Class<?> itemType = type.getComponentType(); Object output = Array.newInstance(itemType, n); while (n-- > 0) Array.set(output, n, cast(Array.get(value, n), itemType)); return output; } } if (Collection.class.isAssignableFrom(type)) // ? -> <? extends Collection> { value = cast(value, Object[].class); // ? -> Object[] if (value.getClass().isArray()) // T1[] -> Vector<T2> { int n = Array.getLength(value); List<Object> output = new Vector<Object>(n); TypeVariable<?>[] itemTypes = type.getTypeParameters(); Class<?> itemType = itemTypes.length > 0 ? itemTypes[0].getClass() : null; while (n-- > 0) { Object item = Array.get(value, n); if (itemType != null) item = cast(item, itemType); // T1 -> T2 output.set(n, item); } return output; } } if (value instanceof String) // String -> ? { String string = (String) value; // String -> primitive if (type == char.class || type == Character.class) return string.charAt(0); if (type == byte.class || type == Byte.class) return Byte.parseByte(string); if (type == long.class || type == Long.class) return Long.parseLong(string); if (type == int.class || type == Integer.class) return Integer.parseInt(string); if (type == short.class || type == Short.class) return Short.parseShort(string); if (type == float.class || type == Float.class) return Float.parseFloat(string); if (type == double.class || type == Double.class) return Double.parseDouble(string); if (type == boolean.class || type == Boolean.class) return string.equalsIgnoreCase("true"); if (type == InputStream.class) // String -> InputStream { try { return new ByteArrayInputStream(string.getBytes("UTF-8")); } catch (Exception e) { return null; } } } if (value instanceof Number) // Number -> primitive { Number number = (Number) value; if (type == byte.class || type == Byte.class) return number.byteValue(); if (type == long.class || type == Long.class) return number.longValue(); if (type == int.class || type == Integer.class) return number.intValue(); if (type == short.class || type == Short.class) return number.shortValue(); if (type == float.class || type == Float.class) return number.floatValue(); if (type == double.class || type == Double.class) return number.doubleValue(); if (type == char.class || type == Character.class) return Character.toChars(number.intValue())[0]; if (type == boolean.class || type == Boolean.class) return !Double.isNaN(number.doubleValue()) && number.intValue() != 0; } } catch (Exception e) { throw new RemoteException(String.format("Unable to cast %s to %s", value.getClass().getSimpleName(), type.getSimpleName()), e); } // Return original value if not handled above. // Primitives and their Object equivalents will cast automatically. return value; }