List of usage examples for java.lang.reflect Field getGenericType
public Type getGenericType()
From source file:org.jiemamy.utils.reflect.ReflectionUtil.java
/** * ?????????/* w ww .j ava 2s . c o m*/ * * @param field * @return ??????? * @throws IndexOutOfBoundsException ???????? parameterPosition????? */ public static Class<?> getElementTypeOfSetFromFieldType(Field field) { Validate.notNull(field); Type type = field.getGenericType(); return getElementTypeOfSet(type); }
From source file:com.github.juanmf.java2plant.Parser.java
protected static void addAggregation(Set<Relation> relations, Class<?> fromType, Field f) { Class<?> delegateType = f.getType(); String varName = f.getName(); String message = varName + ": " + TypesHelper.getSimpleName(f.getGenericType().toString()); String toCardinal = "1"; String toName = delegateType.getName(); if (isMulti(delegateType)) { toCardinal = "*"; if (!delegateType.isArray()) { Set<String> typeVars = getTypeParams(f); for (String type : typeVars) { Relation aggregation = new Aggregation(fromType, type, f, toCardinal, message); relations.add(aggregation); }//from w ww. ja v a 2 s . co m return; } toName = CanonicalName.getClassName(delegateType.getName()); } Relation aggregation = new Aggregation(fromType, toName, f, toCardinal, message); relations.add(aggregation); }
From source file:es.logongas.ix3.util.ReflectionUtil.java
public static boolean isFieldParametrizedList(Field field, Class listClass) { Type type = field.getGenericType(); if (type instanceof ParameterizedType) { ParameterizedType parameterizedType = (ParameterizedType) type; if (parameterizedType.getRawType().equals(List.class)) { Type[] actualTypeArguments = parameterizedType.getActualTypeArguments(); if ((actualTypeArguments == null) || (actualTypeArguments.length != 1)) { return false; } else { if (actualTypeArguments[0].equals(listClass)) { return true; } else { return false; }//from ww w .j ava2 s.co m } } else { return false; } } else { return false; } }
From source file:de.micromata.genome.util.runtime.ClassUtils.java
/** * Find generic type from field./*from w w w . java 2 s.com*/ * * @param clazz the clazz * @param field the field * @param pos the pos * @return the class */ public static Class<?> findGenericTypeFromField(Class<?> clazz, Field field, int pos) { java.lang.reflect.Type gent = field.getGenericType(); Class<?> gentype = ClassUtils.findGenericTypeArgument(gent, pos); return gentype; }
From source file:org.batoo.jpa.common.reflect.ReflectHelper.java
/** * Returns the actual generic type of a class's type parameter of the <code>member</code>. * <p>/*from ww w . j av a2s . co m*/ * if the <code>member</code> is a field then field's generic types are checked. Otherwise the <code>member</code> is treated a a method * and its return type's is checked. * <p> * * @param member * the member * @param index * the index number of the generic parameter * @return the class of generic type * * @param <X> * the type of the class * * @since $version * @author hceylan */ @SuppressWarnings("unchecked") public static <X> Class<X> getGenericType(Member member, int index) { Type type; if (member instanceof Field) { final Field field = (Field) member; type = field.getGenericType(); } else { final Method method = (Method) member; type = method.getGenericReturnType(); } // if not a parameterized type return null if (!(type instanceof ParameterizedType)) { return null; } final ParameterizedType parameterizedType = (ParameterizedType) type; final Type[] types = parameterizedType != null ? parameterizedType.getActualTypeArguments() : null; return (Class<X>) ((types != null) && (index < types.length) ? types[index] : null); }
From source file:utils.ReflectionService.java
public static JsonNode createJsonNode(Class clazz, int maxDeep) { if (maxDeep <= 0 || JsonNode.class.isAssignableFrom(clazz)) { return null; }/*from ww w. j ava2s . co m*/ ObjectMapper objectMapper = new ObjectMapper(); ObjectNode objectNode = objectMapper.createObjectNode(); for (Field field : clazz.getDeclaredFields()) { field.setAccessible(true); String key = field.getName(); try { // is array or collection if (field.getType().isArray() || Collection.class.isAssignableFrom(field.getType())) { ParameterizedType collectionType = (ParameterizedType) field.getGenericType(); Class<?> type = (Class<?>) collectionType.getActualTypeArguments()[0]; ArrayNode arrayNode = objectMapper.createArrayNode(); arrayNode.add(createJsonNode(type, maxDeep - 1)); objectNode.put(key, arrayNode); } else { Class<?> type = field.getType(); if (Modifier.isStatic(field.getModifiers())) { continue; } else if (type.isEnum()) { objectNode.put(key, Enum.class.getName()); } else if (!type.getName().startsWith("java") && !key.startsWith("_")) { objectNode.put(key, createJsonNode(type, maxDeep - 1)); } else { objectNode.put(key, type.getName()); } } } catch (Exception e) { e.printStackTrace(); } } return objectNode; }
From source file:es.logongas.ix3.util.ReflectionUtil.java
public static boolean isFieldParametrizedMap(Field field, Class keyClass, Class valueClass) { Type type = field.getGenericType(); if (type instanceof ParameterizedType) { ParameterizedType parameterizedType = (ParameterizedType) type; if (parameterizedType.getRawType().equals(Map.class)) { Type[] actualTypeArguments = parameterizedType.getActualTypeArguments(); if ((actualTypeArguments == null) || (actualTypeArguments.length != 2)) { return false; } else { if ((actualTypeArguments[0].equals(keyClass)) && (actualTypeArguments[1].equals(valueClass))) { return true; } else { return false; }//w w w .ja v a 2 s .c o m } } else { return false; } } else { return false; } }
From source file:com.initialxy.cordova.themeablebrowser.ThemeableBrowserUnmarshaller.java
/** * Given a JSONObject, unmarhall it to an instance of the given class. * * @param jsonObj JSON string to unmarshall. * @param cls Return an instance of this class. Must be either public class * or private static class. Inner class will not work. * @param <T> Same type as cls./*from w w w . ja va 2 s.com*/ * @return An instance of class given by cls. * @throws com.initialxy.cordova.themeablebrowser.ThemeableBrowserUnmarshaller.TypeMismatchException */ public static <T> T JSONToObj(JSONObject jsonObj, Class<T> cls) { T result = null; try { Constructor<T> constructor = cls.getDeclaredConstructor(); constructor.setAccessible(true); result = (T) constructor.newInstance(); Iterator<?> i = jsonObj.keys(); while (i.hasNext()) { String k = (String) i.next(); Object val = jsonObj.get(k); try { Field field = cls.getField(k); Object converted = valToType(val, field.getGenericType()); if (converted == null) { if (!field.getType().isPrimitive()) { field.set(result, null); } else { throw new TypeMismatchException( String.format("Type %s cannot be set to null.", field.getType())); } } else { if (converted instanceof List && field.getType().isAssignableFrom(List.class)) { // Class can define their own favorite // implementation of List. In which case the field // still need to be defined as List, but it can be // initialized with a placeholder instance of any of // the List implementations (eg. ArrayList). Object existing = field.get(result); if (existing != null) { ((List<?>) existing).clear(); // Just because I don't want javac to complain // about unsafe operations. So I'm gonna use // more reflection, HA! Method addAll = existing.getClass().getMethod("addAll", Collection.class); addAll.invoke(existing, converted); } else { field.set(result, converted); } } else { field.set(result, converted); } } } catch (NoSuchFieldException e) { // Ignore. } catch (IllegalAccessException e) { // Ignore. } catch (IllegalArgumentException e) { // Ignore. } } } catch (JSONException e) { throw new ParserException(e); } catch (NoSuchMethodException e) { throw new ClassInstantiationException("Failed to retrieve constructor for " + cls.toString() + ", make sure it's not an inner class."); } catch (InstantiationException e) { throw new ClassInstantiationException(cls); } catch (IllegalAccessException e) { throw new ClassInstantiationException(cls); } catch (InvocationTargetException e) { throw new ClassInstantiationException(cls); } return result; }
From source file:org.xwiki.store.datanucleus.internal.DataNucleusPersistableObjectStore.java
/** * Walk the elements in a collection or array looking for persistable objects. * * @param id the identifier for the object. * @param value the collction or array to walk, if this is not a collection or array, * nothing will be done./* www . j a v a 2 s . c o m*/ * @param out, the output into which all discovered persistable objects will be placed. * @param stack a stack used for internal loop detection. */ private static void walkTree(final String id, final Object value, final Map<String, PersistableObject> out, final Stack stack) { if (value == null || stack.contains(value)) { return; } stack.push(value); if (value instanceof PersistableObject) { out.put(id, (PersistableObject) value); // Index over the fields looking for more persistables for (final Field field : value.getClass().getDeclaredFields()) { final Class type = field.getType(); boolean isMap = Map.class.isAssignableFrom(type); if (isMap || Collection.class.isAssignableFrom(type)) { final ParameterizedType pType = (ParameterizedType) field.getGenericType(); final Class<?> componentType = (Class<?>) pType.getActualTypeArguments()[isMap ? 1 : 0]; if (!potentiallyPersistable(componentType)) { continue; } } else if (type.isArray()) { if (!potentiallyPersistable(type.getComponentType())) { continue; } } else if (!potentiallyPersistable(type)) { continue; } // We don't need to use reflection for this, we can use the jdo state manager. field.setAccessible(true); try { walkTree(id + "." + field.getName(), field.get(value), out, stack); } catch (IllegalAccessException e) { throw new UnexpectedException( "Could not reflect nested objects, " + "is a security manager preventing it?"); } } } else { walkCollection(id, value, out, stack); } stack.pop(); return; }
From source file:org.apache.camel.maven.DocumentGeneratorMojo.java
public static String getCanonicalName(Field field) { final Type fieldType = field.getGenericType(); if (fieldType instanceof ParameterizedType) { return getCanonicalName((ParameterizedType) fieldType); } else {/*from www.j a va 2s . c o m*/ return getCanonicalName(field.getType()); } }