List of usage examples for java.lang.reflect Field getGenericType
public Type getGenericType()
From source file:org.appverse.web.framework.backend.api.converters.helpers.ConverterUtils.java
/** * Copy source bean collection properties of type bean to target bean as * detached bean collections//from w ww .java 2 s . c om * * @param sourceBean * Source Bean * @param targetBean * Target Bean * @param childrenBeanConverters * List of converters needed to convert source bean childs of * type bean collection to target bean childs of type bean * collection * @param sourceFields * Fields of source Bean * @throws Exception */ private static void convertBeanCollectionFields(AbstractBean sourceBean, AbstractBean targetBean, IBeanConverter[] childrenBeanConverters, Field[] sourceFields) throws Exception { // Arrays to hold bean collection field names, target collection types, // source collection parameter types and target collection parameter // types String[] beanCollectionFieldNames = new String[0]; Type[] targetFieldTypes = new Type[0]; Type[] sourceFieldParameterTypes = new Type[0]; Type[] targetFieldParameterTypes = new Type[0]; // For each source field... for (Field field : sourceFields) { // If source field is a collection... if (Collection.class.isAssignableFrom(field.getType())) { // Get Field (Remember is a collection) parameters Type[] sourceFieldParameters = ((ParameterizedType) field.getGenericType()) .getActualTypeArguments(); // If field is a collection of something extending // AbstractBean... if (sourceFieldParameters.length == 1 && AbstractBean.class.isAssignableFrom((Class<?>) sourceFieldParameters[0])) { // If target field is a collection if (Collection.class .isAssignableFrom(targetBean.getClass().getDeclaredField(field.getName()).getType())) { // Get target field parameter types Type[] targetFieldParameters = ((ParameterizedType) targetBean.getClass() .getDeclaredField(field.getName()).getGenericType()).getActualTypeArguments(); // If target field is a collection of something // extending // AbstractBean... if (targetFieldParameters.length == 1 && AbstractBean.class.isAssignableFrom((Class<?>) targetFieldParameters[0])) { // Fill Arrays with name, source field type, target // type and target // parameter type beanCollectionFieldNames = (String[]) ArrayUtils.add(beanCollectionFieldNames, field.getName()); targetFieldTypes = (Type[]) ArrayUtils.add(targetFieldTypes, targetBean.getClass().getDeclaredField(field.getName()).getType()); sourceFieldParameterTypes = (Type[]) ArrayUtils.add(sourceFieldParameterTypes, sourceFieldParameters[0]); targetFieldParameterTypes = (Type[]) ArrayUtils.add(targetFieldParameterTypes, targetFieldParameters[0]); } else { throw new Exception("Target collection parameter type mismatch"); } } else { throw new Exception("Target parameter type mismatch"); } } } } // For each field with collection of bean type... for (int i = 0; i < beanCollectionFieldNames.length; i++) { String beanCollectionFieldName = beanCollectionFieldNames[i]; Type targetFieldType = targetFieldTypes[i]; Type sourceFieldParameterType = sourceFieldParameterTypes[i]; Type targetFieldParameterType = targetFieldParameterTypes[i]; // Select the appropiate converter... IBeanConverter converter = getConverter(childrenBeanConverters, sourceFieldParameterType, targetFieldParameterType); // Create a target detached (LazyArrayList) collection using the // source collection, the target parameter type y the converter... @SuppressWarnings("unchecked") IndirectArrayList<AbstractBean, AbstractBean> lazyCollection = new IndirectArrayList<AbstractBean, AbstractBean>( (List<AbstractBean>) getGetterMethod(beanCollectionFieldName, sourceBean).invoke(sourceBean), (Class<AbstractBean>) targetFieldParameterType, converter); // Set the detached collection on target bean getSetterMethod(beanCollectionFieldName, targetFieldType, targetBean).invoke(targetBean, lazyCollection); } }
From source file:at.ac.tuwien.infosys.jcloudscale.utility.ReflectionUtil.java
public static void checkLegalCloudInvocationInfoDef(Object obj) { for (Field f : obj.getClass().getDeclaredFields()) { if (f.getAnnotation(CloudInvocationInfos.class) != null) { Type[] genericTypes = ((ParameterizedType) f.getGenericType()).getActualTypeArguments(); Class<?> typeParameter = (Class<?>) genericTypes[0]; if (!f.getType().equals(List.class) || genericTypes.length != 1 || !typeParameter.equals(InvocationInfo.class)) throw new IllegalDefinitionException("Illegal field type " + f.getType().getName() + " annotated with " + "@CloudInvocationInfos. You may only annotate java.util.List<InvocationInfo> fields."); if (Modifier.isStatic(f.getModifiers())) throw new IllegalDefinitionException("Illegal field " + f.getName() + " annotated with @CloudInvocationInfos. " + "Field has to be non-static."); }//from w w w . jav a 2s . c o m } }
From source file:org.jtester.utility.ReflectionUtils.java
/** * Gets the T from a Class<T> field declaration. An exception is raised if * the field type is not generic or has more than 1 generic type * // ww w. j a v a 2s . c om * @param field * The field to get the type from, not null * @return The declared generic type */ public static Type getGenericType(Field field) { Type type = field.getGenericType(); if (type instanceof ParameterizedType) { Type[] argumentTypes = ((ParameterizedType) type).getActualTypeArguments(); if (argumentTypes.length == 1) { return argumentTypes[0]; } throw new JTesterException("Unable to determine unique generic type for field: " + field + ". The field type declares more than one generic type: " + type); } throw new JTesterException("Unable to determine unique generic type for field: " + field + ". Field type is not a generic type: " + type); }
From source file:com.github.gekoh.yagen.util.MappingUtils.java
public static Class determineTargetEntity(AccessibleObject ao, Class<?> specifiedTargetEntity) { String errorMessage = "targetEntity not present and not determinable (need generic declaration)"; try {//from w ww . j ava 2 s .c o m if (specifiedTargetEntity != null && specifiedTargetEntity != Void.TYPE) { return specifiedTargetEntity; } else { if (ao instanceof Field) { Field f = (Field) ao; if (Collection.class.isAssignableFrom(f.getType())) { // this has to work, because otherwise the target entity must be valid ParameterizedType type = (ParameterizedType) f.getGenericType(); return (Class<?>) type.getActualTypeArguments()[0]; } return f.getType(); } else if (ao instanceof Method) { Method m = (Method) ao; if (Collection.class.isAssignableFrom(m.getReturnType())) { // this has to work, because otherwise the target entity must be valid ParameterizedType type = (ParameterizedType) m.getGenericReturnType(); return (Class<?>) type.getActualTypeArguments()[0]; } return m.getReturnType(); } } } catch (Exception e) { throw new IllegalStateException(errorMessage, e); } throw new IllegalStateException(errorMessage); }
From source file:org.jtester.utility.ReflectionUtils.java
/** * Returns all declared fields of the given class that are assignable from * the given type.// w ww .j av a 2 s. c o m * * @param clazz * The class to get fields from, not null * @param type * The type, not null * @param isStatic * True if static fields are to be returned, false for non-static * @return A list of Fields, empty list if none found */ public static Set<Field> getFieldsAssignableFrom(Class<?> clazz, Type type, boolean isStatic) { Set<Field> fieldsOfType = new HashSet<Field>(); Set<Field> allFields = getAllFields(clazz); for (Field field : allFields) { if (isAssignable(type, field.getGenericType()) && isStatic(field.getModifiers()) == isStatic) { fieldsOfType.add(field); } } return fieldsOfType; }
From source file:de.adesso.referencer.search.helper.MyHelpMethods.java
public static Class getClassFromListOfClasses(Field f) { try {/*from w ww. ja v a 2 s. c o m*/ // System.out.println("f="+f.toString()); // System.out.println("f.getGenericType()="+f.getGenericType().toString()); ParameterizedType listType = (ParameterizedType) f.getGenericType(); Class<?> listClass = (Class<?>) listType.getActualTypeArguments()[0]; return listClass; } catch (Exception e) { e.printStackTrace(); return null; } // return null; }
From source file:org.unitils.util.ReflectionUtils.java
/** * Gets the T from a Class<T> field declaration. An exception is raised if * the field type is not generic or has more than 1 generic type * //from w w w . j a va 2s . c om * @param field * The field to get the type from, not null * @return The declared generic type */ public static Type getGenericType(Field field) { Type type = field.getGenericType(); if (type instanceof ParameterizedType) { Type[] argumentTypes = ((ParameterizedType) type).getActualTypeArguments(); if (argumentTypes.length == 1) { return argumentTypes[0]; } throw new UnitilsException("Unable to determine unique generic type for field: " + field + ". The field type declares more than one generic type: " + type); } throw new UnitilsException("Unable to determine unique generic type for field: " + field + ". Field type is not a generic type: " + type); }
From source file:org.mstc.zmq.json.Decoder.java
@SuppressWarnings("unchecked") public static void decode(String input, Field[] fields, Object b) throws IOException { ObjectMapper mapper = new ObjectMapper(); mapper.enable(DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS); if (logger.isDebugEnabled()) logger.debug(input);/*from w ww. ja v a 2 s . c o m*/ JsonFactory factory = mapper.getFactory(); try (JsonParser jp = factory.createParser(input)) { /* Sanity check: verify that we got "Json Object" */ if (jp.nextToken() != JsonToken.START_OBJECT) { throw new IOException("Expected data to start with an Object"); } /* Iterate over object fields */ while (jp.nextToken() != JsonToken.END_OBJECT) { String fieldName = jp.getCurrentName(); jp.nextToken(); Field field = getField(fieldName, fields); if (field == null) { throw new IOException( "Could not find field [" + fieldName + "] on class " + b.getClass().getName()); } try { if (field.getType().isAssignableFrom(List.class)) { String adder = getAdder(fieldName); TypeFactory t = TypeFactory.defaultInstance(); ParameterizedType listType = (ParameterizedType) field.getGenericType(); Class<?> listClass = (Class<?>) listType.getActualTypeArguments()[0]; List list = mapper.readValue(jp.getValueAsString(), t.constructCollectionType(List.class, listClass)); Method m = b.getClass().getDeclaredMethod(adder, Collection.class); m.invoke(b, list); } else if (field.getType().isArray()) { Class<?> type = field.getType(); String setter = getSetter(fieldName); Method m = b.getClass().getDeclaredMethod(setter, field.getType()); logger.info("Field {} is array of {}[], {}, using method {}", field.getName(), field.getType().getComponentType(), jp.getCurrentToken().name(), m); if (jp.getCurrentToken().id() == JsonToken.START_ARRAY.id()) { List list = new ArrayList(); while (jp.nextToken() != JsonToken.END_ARRAY) { String value = jp.getText(); switch (jp.getCurrentToken()) { case VALUE_STRING: list.add(value); break; case VALUE_NUMBER_INT: if (type.getComponentType().isAssignableFrom(double.class)) { list.add(Double.parseDouble(value)); } else if (type.getComponentType().isAssignableFrom(float.class)) { list.add(Float.parseFloat(value)); } else { list.add(Integer.parseInt(value)); } break; case VALUE_NUMBER_FLOAT: logger.info("Add float"); list.add(jp.getFloatValue()); break; case VALUE_NULL: break; default: logger.warn("[3] Not sure how to handle {} yet", jp.getCurrentToken().name()); } } Object array = Array.newInstance(field.getType().getComponentType(), list.size()); for (int i = 0; i < list.size(); i++) { Object val = list.get(i); Array.set(array, i, val); } m.invoke(b, array); } else { if (type.getComponentType().isAssignableFrom(byte.class)) { m.invoke(b, jp.getBinaryValue()); } } } else { String setter = getSetter(fieldName); logger.debug("{}: {}", setter, field.getType().getName()); Method m = b.getClass().getDeclaredMethod(setter, field.getType()); switch (jp.getCurrentToken()) { case VALUE_STRING: m.invoke(b, jp.getText()); break; case VALUE_NUMBER_INT: m.invoke(b, jp.getIntValue()); break; case VALUE_NUMBER_FLOAT: m.invoke(b, jp.getFloatValue()); break; case VALUE_NULL: logger.debug("Skip invoking {}.{}, property is null", b.getClass().getName(), m.getName()); break; case START_OBJECT: StringBuilder sb = new StringBuilder(); while (jp.nextToken() != JsonToken.END_OBJECT) { switch (jp.getCurrentToken()) { case VALUE_STRING: sb.append("\"").append(jp.getText()).append("\""); break; case FIELD_NAME: if (sb.length() > 0) sb.append(","); sb.append("\"").append(jp.getText()).append("\"").append(":"); break; case VALUE_NUMBER_INT: sb.append(jp.getIntValue()); break; case VALUE_NUMBER_FLOAT: sb.append(jp.getFloatValue()); break; case VALUE_NULL: sb.append("null"); break; default: logger.warn("[2] Not sure how to handle {} yet", jp.getCurrentToken().name()); } } String s = String.format("%s%s%s", JsonToken.START_OBJECT.asString(), sb.toString(), JsonToken.END_OBJECT.asString()); Object parsed = getNested(field.getType(), s.getBytes()); m.invoke(b, parsed); break; default: logger.warn("[1] Not sure how to handle {} yet", jp.getCurrentToken().name()); } } } catch (InvocationTargetException | NoSuchMethodException | IllegalAccessException | IllegalArgumentException e) { logger.error("Failed setting field [{}], builder: {}", fieldName, b.getClass().getName(), e); } } } }
From source file:org.diorite.cfg.system.ConfigField.java
public static Set<Class<?>> getAllPossibleTypes(final Field field) { final Set<Class<?>> classes = new HashSet<>(1); classes.add(field.getType());/* w w w . j a va 2s.co m*/ getAllPossibleTypes(classes, new HashSet<>(5), field.getGenericType()); return classes; }
From source file:org.uimafit.factory.ConfigurationParameterFactory.java
private static String getConfigurationParameterType(Field field) { Class<?> parameterClass = field.getType(); String parameterClassName;// ww w. j a v a 2 s. c o m if (parameterClass.isArray()) { parameterClassName = parameterClass.getComponentType().getName(); } else if (Collection.class.isAssignableFrom(parameterClass)) { ParameterizedType collectionType = (ParameterizedType) field.getGenericType(); parameterClassName = ((Class<?>) (collectionType.getActualTypeArguments()[0])).getName(); } else { parameterClassName = parameterClass.getName(); } String parameterType = javaUimaTypeMap.get(parameterClassName); if (parameterType == null) { return ConfigurationParameter.TYPE_STRING; } return parameterType; }