Java Code Examples for java.lang.reflect.Field.getGenericType()

The following are Jave code examples for showing how to use getGenericType() of the java.lang.reflect.Field class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: xproject   File: ReflectionUtils.java   View Source Code Vote up 7 votes
@SuppressWarnings("rawtypes")
public static Class getFieldGenricType(final Field field, final int index) {
   	Assert.notNull(field, "Parameter 'field' must be not null!");
   	Assert.state(index > -1, "Parameter 'index' must be > -1!");
   	Type type = field.getGenericType();
   	if(type instanceof ParameterizedType){
		ParameterizedType ptype = (ParameterizedType)type;
		type = ptype.getActualTypeArguments()[index];
		if(type instanceof ParameterizedType){
			return (Class)((ParameterizedType) type).getRawType();
		}else{
			return (Class) type;
		}
	}else{
		return (Class) type;
	}
   }
 
Example 2
Project: jrpip   File: ClassTypeHelper.java   View Source Code Vote up 6 votes
public static boolean isFieldPrintable(Field field)
{
    boolean isPrintable = false;
    Type fieldType = field.getGenericType();
    if (fieldType instanceof ParameterizedType)
    {
        Type[] declaredGenericTypes = ((ParameterizedType) fieldType).getActualTypeArguments();
        for (Type type : declaredGenericTypes)
        {
            isPrintable = ClassTypeHelper.isPrintableClass((Class<?>) type);
            if (!isPrintable)
            {
                break;
            }
        }
    }
    return isPrintable;
}
 
Example 3
Project: hibatis   File: CollectionProperty.java   View Source Code Vote up 6 votes
public CollectionProperty(EntityMetadata metadata, Field field) {
	super(metadata, field);
	Collection collection = field.getAnnotation(Collection.class);
	if(!java.util.Collection.class.isAssignableFrom(field.getType())){
		throw new HibatisException("Collection属性必须为集合类型");
	}
	this.isLazy = collection.lazy();
	this.isIn = collection.in();
	this.cacheable = collection.cacheable();
	ParameterizedType type = (ParameterizedType) field.getGenericType();
	this.referenceType = (Class<?>) type.getActualTypeArguments()[0];
	this.rawType = field.getType();
	if(this.rawType != List.class){
		throw new HibatisException("@Collection只支持java.util.List类型");
	}
	this.setProperties(collection.property());
	this.setReferences(collection.reference());
	String[] orderBy = collection.orderBy();
	if(orderBy != null){
		sorts = new Sort[orderBy.length];
		for (int i = 0; i < sorts.length; i++) {
			String order = orderBy[i];
			sorts[i] = Sort.parse(order);
		}
	}
}
 
Example 4
Project: MagicBox   File: GenericCollection.java   View Source Code Vote up 6 votes
@Override
public final boolean check(Field field) {
    if (field == null)
        return false;

    Type type = field.getGenericType();

    if (type instanceof ParameterizedType) {
        ParameterizedType parameterizedType = (ParameterizedType) type;
        Type rawType = parameterizedType.getRawType();

        if (rawType.equals(collectionType)) {
            return checkGenericType(parameterizedType);
        } else
            return false;
    }
    return false;
}
 
Example 5
Project: aaden-pay   File: XmlUtils.java   View Source Code Vote up 6 votes
/**
 * 给List中的泛型取别名
 * 
 * @param xStream
 * @param obj
 */
private static void toListGenericsAlias(XStream xStream, Object obj) {
	/** 得到所有的fields **/
	Field[] fs = obj.getClass().getDeclaredFields();
	for (Field f : fs) {
		/** 得到field的class及类型全路径 **/
		Class<?> fieldClazz = f.getType();
		/** 如果是List类型,得到其类的类型 **/
		if (fieldClazz.isAssignableFrom(List.class)) {
			/** 获取类的类型 **/
			Type fc = f.getGenericType();
			if (fc == null)
				continue;
			/** 是否是参数化泛型类型 **/
			if (fc instanceof ParameterizedType) {
				/** 得到泛型里的class类型对象 **/
				ParameterizedType pt = (ParameterizedType) fc;
				Class<?> genericClazz = (Class<?>) pt.getActualTypeArguments()[0];
				xStream.alias(genericClazz.getSimpleName(), genericClazz);
			}
		}
	}
}
 
Example 6
Project: GitHub   File: LitePalBase.java   View Source Code Vote up 5 votes
/**
 * Get the generic type class of List or Set. If there's no generic type of
 * List or Set return null.
 *
 * @param field
 *            A generic type field.
 * @return The generic type of List or Set.
 */
protected Class<?> getGenericTypeClass(Field field) {
    Type genericType = field.getGenericType();
    if (genericType != null) {
        if (genericType instanceof ParameterizedType) {
            ParameterizedType parameterizedType = (ParameterizedType) genericType;
            return (Class<?>) parameterizedType.getActualTypeArguments()[0];
        }
    }
    return null;
}
 
Example 7
Project: saluki   File: Protobuf2PojoHelp.java   View Source Code Vote up 5 votes
private static Object convertCollectionFromProtobufs(Field field,
    Collection<?> collectionOfProtobufs)
    throws JException, InstantiationException, IllegalAccessException {
  if (collectionOfProtobufs.isEmpty()) {
    return collectionOfProtobufs;
  }
  final ParameterizedType listType = (ParameterizedType) field.getGenericType();
  final Class<?> collectionClazzType = (Class<?>) listType.getActualTypeArguments()[0];
  final ProtobufEntity protoBufEntityAnno =
      ProtobufSerializerUtils.getProtobufEntity(collectionClazzType);
  final Object first = collectionOfProtobufs.toArray()[0];
  if (!(first instanceof Message) && protoBufEntityAnno == null) {
    return collectionOfProtobufs;
  }
  final Collection<Object> newCollectionOfValues = new ArrayList<>();
  for (Object protobufValue : collectionOfProtobufs) {
    if (!(protobufValue instanceof Message)) {
      throw new ProtobufException(
          "Collection contains an object of type " + protobufValue.getClass()
              + " which is not an instanceof GeneratedMessage, can not (de)serialize this");
    }
    newCollectionOfValues
        .add(serializeFromProtobufEntity((Message) protobufValue, collectionClazzType));
  }

  return newCollectionOfValues;
}
 
Example 8
Project: strongbox   File: GenericFile.java   View Source Code Vote up 5 votes
private Class<?> getConvertedType(String fieldName) {
    try {
        Field field = clazz.getField(fieldName);

        if (field.getType().equals(Optional.class)) {
            ParameterizedType type = (ParameterizedType) field.getGenericType();
            return converters.getConvertedType((Class<?>) type.getActualTypeArguments()[0]);
        } else {
            return converters.getConvertedType(field.getType());
        }
    } catch (NoSuchFieldException e) {
        throw new FieldAccessException(fieldName, clazz.getName());
    }

}
 
Example 9
Project: framework   File: CommonUtils.java   View Source Code Vote up 5 votes
public static Class<?>[] getFieldGenericType(Field field) {
	Type genericFieldType = field.getGenericType();

	if (genericFieldType instanceof ParameterizedType) {
		ParameterizedType aType = (ParameterizedType) genericFieldType;
		Type[] fieldArgTypes = aType.getActualTypeArguments();
		return (Class<?>[]) fieldArgTypes;
	}
	return null;
}
 
Example 10
Project: r8   File: Minifygeneric.java   View Source Code Vote up 5 votes
public static void main(String[] args) throws NoSuchMethodException, SecurityException, NoSuchFieldException {
  for (TypeVariable<Class<Generic>> var : Generic.class.getTypeParameters()) {
    System.out.println(var.getName());
    Type bound = var.getBounds()[0];
    System.out.println(((Class<?>) bound).getName().equals(AA.class.getName()));
  }

  Field f = Generic.class.getField("f");
  ParameterizedType fieldType = (java.lang.reflect.ParameterizedType)f.getGenericType();
  checkOneParameterType(fieldType, Generic.class, AA.class);

  ParameterizedType methodReturnType =
      (ParameterizedType) Generic.class.getMethod("get").getGenericReturnType();
  checkOneParameterType(methodReturnType, Generic.class, AA.class);
}
 
Example 11
Project: yadaframework   File: YadaUtil.java   View Source Code Vote up 5 votes
/**
 * Reflection to get the type of a given field, even nested or in a superclass.
 * @param rootClass
 * @param attributePath field name like "surname" or even a path like "friend.name"
 * @return
 * @throws NoSuchFieldException if the field is not found in the class hierarchy
 * @throws SecurityException
 */
public Class getType(Class rootClass, String attributePath) throws NoSuchFieldException, SecurityException {
	if (StringUtils.isBlank(attributePath)) {
		return rootClass;
	}
	String attributeName = StringUtils.substringBefore(attributePath, ".");
	Field field = null;
	NoSuchFieldException exception = null;
	while (field==null && rootClass!=null) {
		try {
			field = rootClass.getDeclaredField(attributeName);
		} catch (NoSuchFieldException e) {
			if (exception==null) {
				exception=e;
			}
			rootClass = rootClass.getSuperclass();
		}
	}
	if (field==null) {
		if (exception!=null) {
			throw exception;
		} else {
			throw new NoSuchFieldException("No field " + attributeName + " found in hierarchy");
		}
	}
	Class attributeType = field.getType();
	// If it's a list, look for the list type
	if (attributeType == java.util.List.class) {
		// TODO check if the attributeType is an instance of java.util.Collection
		ParameterizedType parameterizedType = (ParameterizedType)field.getGenericType();
		if (parameterizedType!=null) {
			Type[] types = parameterizedType.getActualTypeArguments();
			if (types.length==1) {
				attributeType = (Class<?>) types[0];
			}
		}
	}
	return getType(attributeType, StringUtils.substringAfter(attributePath, "."));
}
 
Example 12
Project: Liteframework   File: FieldUtil.java   View Source Code Vote up 5 votes
/**
 * 获取域的泛型类型,如果不带泛型返回null
 *
 * @param f
 * @return
 */
public static Class<?> getGenericType(Field f) {
    Type type = f.getGenericType();
    if (type instanceof ParameterizedType) {
        type = ((ParameterizedType) type).getActualTypeArguments()[0];
        if (type instanceof Class<?>) return (Class<?>) type;
    } else if (type instanceof Class<?>) return (Class<?>) type;
    return null;
}
 
Example 13
Project: uavstack   File: ASMUtils.java   View Source Code Vote up 5 votes
public static Type getFieldType(Class<?> clazz, String fieldName) {
    try {
        Field field = clazz.getField(fieldName);

        return field.getGenericType();
    } catch (Exception ex) {
        return null;
    }
}
 
Example 14
Project: Jupiter   File: SimpleConfig.java   View Source Code Vote up 4 votes
public boolean load() {
    if (!this.configFile.exists()) return false;
    Config cfg = new Config(configFile, Config.YAML);
    for (Field field : this.getClass().getDeclaredFields()) {
        if (field.getName().equals("configFile")) continue;
        if (skipSave(field)) continue;
        String path = getPath(field);
        if (path == null) continue;
        if (path.isEmpty()) continue;
        field.setAccessible(true);
        try {
            if (field.getType() == int.class || field.getType() == Integer.class)
                field.set(this, cfg.getInt(path, field.getInt(this)));
            else if (field.getType() == boolean.class || field.getType() == Boolean.class)
                field.set(this, cfg.getBoolean(path, field.getBoolean(this)));
            else if (field.getType() == long.class || field.getType() == Long.class)
                field.set(this, cfg.getLong(path, field.getLong(this)));
            else if (field.getType() == double.class || field.getType() == Double.class)
                field.set(this, cfg.getDouble(path, field.getDouble(this)));
            else if (field.getType() == String.class)
                field.set(this, cfg.getString(path, (String) field.get(this)));
            else if (field.getType() == ConfigSection.class)
                field.set(this, cfg.getSection(path));
            else if (field.getType() == List.class) {
                Type genericFieldType = field.getGenericType();
                if (genericFieldType instanceof ParameterizedType) {
                    ParameterizedType aType = (ParameterizedType) genericFieldType;
                    Class fieldArgClass = (Class) aType.getActualTypeArguments()[0];
                    if (fieldArgClass == Integer.class) field.set(this, cfg.getIntegerList(path));
                    else if (fieldArgClass == Boolean.class) field.set(this, cfg.getBooleanList(path));
                    else if (fieldArgClass == Double.class) field.set(this, cfg.getDoubleList(path));
                    else if (fieldArgClass == Character.class) field.set(this, cfg.getCharacterList(path));
                    else if (fieldArgClass == Byte.class) field.set(this, cfg.getByteList(path));
                    else if (fieldArgClass == Float.class) field.set(this, cfg.getFloatList(path));
                    else if (fieldArgClass == Short.class) field.set(this, cfg.getFloatList(path));
                    else if (fieldArgClass == String.class) field.set(this, cfg.getStringList(path));
                } else field.set(this, cfg.getList(path)); // Hell knows what's kind of List was found :)
            } else
                throw new IllegalStateException("SimpleConfig did not supports class: " + field.getType().getName() + " for config field " + configFile.getName());
        } catch (Exception e) {
            Server.getInstance().getLogger().logException(e);
            return false;
        }
    }
    return true;
}
 
Example 15
Project: xxl-crawler   File: FieldReflectionUtil.java   View Source Code Vote up 4 votes
/**
 * 参数解析 (支持:Byte、Boolean、String、Short、Integer、Long、Float、Double、Date)
 *
 * @param field
 * @param value
 * @return
 */
public static Object parseValue(Field field, String value) {

	Class<?> fieldType = field.getType();

	// parse list item
	if (field.getGenericType() instanceof ParameterizedType) {
		ParameterizedType fieldGenericType = (ParameterizedType) field.getGenericType();
		if (fieldGenericType.getRawType().equals(List.class)) {
			Type gtATA = fieldGenericType.getActualTypeArguments()[0];
			fieldType = (Class<?>) gtATA;
		}
	}

	PageFieldSelect apiRequestParam = field.getAnnotation(PageFieldSelect.class);

	if(value==null || value.trim().length()==0)
		return null;
	value = value.trim();

	 if (Byte.class.equals(fieldType) || Byte.TYPE.equals(fieldType)) {
		return parseByte(value);
	} else if (Boolean.class.equals(fieldType) || Boolean.TYPE.equals(fieldType)) {
		return parseBoolean(value);
	}/* else if (Character.class.equals(fieldType) || Character.TYPE.equals(fieldType)) {
		 return value.toCharArray()[0];
	}*/ else if (String.class.equals(fieldType)) {
		return value;
	} else if (Short.class.equals(fieldType) || Short.TYPE.equals(fieldType)) {
		 return parseShort(value);
	} else if (Integer.class.equals(fieldType) || Integer.TYPE.equals(fieldType)) {
		return parseInt(value);
	} else if (Long.class.equals(fieldType) || Long.TYPE.equals(fieldType)) {
		return parseLong(value);
	} else if (Float.class.equals(fieldType) || Float.TYPE.equals(fieldType)) {
		return parseFloat(value);
	} else if (Double.class.equals(fieldType) || Double.TYPE.equals(fieldType)) {
		return parseDouble(value);
	} else if (Date.class.equals(fieldType)) {
		 return parseDate(apiRequestParam, value);

	} else {
		throw new RuntimeException("request illeagal type, type must be Integer not int Long not long etc, type=" + fieldType);
	}
}
 
Example 16
Project: Jenisys3   File: SimpleConfig.java   View Source Code Vote up 4 votes
public boolean load() {
    if (!this.configFile.exists()) return false;
    Config cfg = new Config(configFile, Config.YAML);
    for (Field field : this.getClass().getDeclaredFields()) {
        if (field.getName().equals("configFile")) continue;
        if (skipSave(field)) continue;
        String path = getPath(field);
        if (path == null) continue;
        if (path.isEmpty()) continue;
        field.setAccessible(true);
        try {
            if (field.getType() == int.class || field.getType() == Integer.class)
                field.set(this, cfg.getInt(path, field.getInt(this)));
            else if (field.getType() == boolean.class || field.getType() == Boolean.class)
                field.set(this, cfg.getBoolean(path, field.getBoolean(this)));
            else if (field.getType() == long.class || field.getType() == Long.class)
                field.set(this, cfg.getLong(path, field.getLong(this)));
            else if (field.getType() == double.class || field.getType() == Double.class)
                field.set(this, cfg.getDouble(path, field.getDouble(this)));
            else if (field.getType() == String.class)
                field.set(this, cfg.getString(path, (String) field.get(this)));
            else if (field.getType() == ConfigSection.class)
                field.set(this, cfg.getSection(path));
            else if (field.getType() == List.class) {
                Type genericFieldType = field.getGenericType();
                if (genericFieldType instanceof ParameterizedType) {
                    ParameterizedType aType = (ParameterizedType) genericFieldType;
                    Class fieldArgClass = (Class) aType.getActualTypeArguments()[0];
                    if (fieldArgClass == Integer.class) field.set(this, cfg.getIntegerList(path));
                    else if (fieldArgClass == Boolean.class) field.set(this, cfg.getBooleanList(path));
                    else if (fieldArgClass == Double.class) field.set(this, cfg.getDoubleList(path));
                    else if (fieldArgClass == Character.class) field.set(this, cfg.getCharacterList(path));
                    else if (fieldArgClass == Byte.class) field.set(this, cfg.getByteList(path));
                    else if (fieldArgClass == Float.class) field.set(this, cfg.getFloatList(path));
                    else if (fieldArgClass == Short.class) field.set(this, cfg.getFloatList(path));
                    else if (fieldArgClass == String.class) field.set(this, cfg.getStringList(path));
                } else field.set(this, cfg.getList(path)); // Hell knows what's kind of List was found :)
            } else
                throw new IllegalStateException("SimpleConfig did not supports class: " + field.getType().getName() + " for config field " + configFile.getName());
        } catch (Exception e) {
            Server.getInstance().getLogger().logException(e);
            return false;
        }
    }
    return true;
}
 
Example 17
Project: spring-jdbc-orm   File: BaseController.java   View Source Code Vote up 4 votes
private Map<String, Object> processFieldError(Map<String, Object> data, Class<?> targetClass, List<FieldError> errors) throws NoSuchFieldException {
    for (FieldError error : errors) {
        String field = error.getField();
        String key = field + error.getCode();
        MsgCode msgCode = null;
        if (null == errorFields.get(key)) {
            String[] pfields = field.split("\\.");
            //判断是否为双层对象并进行切割获取字段对象的字段并抓取code
            if (pfields.length >= 2) {
                String temp = pfields[0];
                if (temp.contains("[")) {
                    temp = temp.substring(0, temp.indexOf("["));
                }
                Field declaredField = targetClass.getDeclaredField(temp);
                Class clazz = declaredField.getType();
                if (clazz.isAssignableFrom(List.class) || clazz.isAssignableFrom(Map.class)) {
                    Type genType = declaredField.getGenericType();
                    if (!(genType instanceof ParameterizedType)) {
                        clazz = Object.class;
                    } else {
                        Type[] params = ((ParameterizedType) genType).getActualTypeArguments();
                        try {
                            clazz = (Class) params[0];
                        } catch (Exception e) {
                            try {
                                clazz = (Class) ((ParameterizedType) params[0]).getRawType();
                            } catch (Exception e1) {
                                e1.printStackTrace();
                            }
                        }
                    }
                }
                msgCode = clazz.getDeclaredField(pfields[1]).getAnnotation(MsgCode.class);
            } else {
                msgCode = targetClass.getDeclaredField(field).getAnnotation(MsgCode.class);
            }
            errorFields.put(key, msgCode);
        } else {
            msgCode = errorFields.get(key);
        }

        if (null != msgCode) {
            data.put(CODE_KEY, errorCode.getCode(msgCode.value()));
        }
        //根据code 在error_code.yml取值,如果未取到值则去默认的error.getDefaultMessage();
        String message = errorCode.getMessage(msgCode != null ? msgCode.value() : null);
        if (null == message) {
            message = error.getDefaultMessage();
        }
        data.put(MESSAGE_KEY, message);
        return data;
    }
    data.put(CODE_KEY, 1000);
    return data;
}
 
Example 18
Project: sdoc   File: DocumentScanner.java   View Source Code Vote up 4 votes
public String formatClass(Class<?> clazz0, List<Class<?>> parents) {
    StringBuilder result = new StringBuilder();
    result.append("{");
    Field[] fields = clazz0.getDeclaredFields();
    int index = 0;
    for (Field field : fields) {
        index++;
        Class<?> clazz = field.getType();
        if (clazz == int.class || clazz == Integer.class || clazz == long.class || clazz == Long.class
                || clazz == double.class || clazz == Double.class || clazz == float.class || clazz == Float.class) {
            result.append("\"").append(field.getName()).append("\"").append(":").append(0);
        } else if (clazz == String.class) {
            result.append("\"").append(field.getName()).append("\"").append(":").append("\"string\"");
        } else if (clazz == boolean.class || clazz == Boolean.class) {
            result.append("\"").append(field.getName()).append("\"").append(":").append("false");
        } else if (clazz == java.util.Date.class || clazz == java.sql.Date.class) {
            result.append("\"").append(field.getName()).append("\"").append(":").append(new Date().getTime());
        } else if (clazz == List.class) {
            Type type = field.getGenericType();
            if (type instanceof ParameterizedType) {
                ParameterizedType paramType = (ParameterizedType) type;
                Type[] actualTypes = paramType.getActualTypeArguments();
                result.append("\"").append(field.getName()).append("\"").append(":");
                // TODO 获取泛型类型,设想只有一个,此处是个数组,有待观察
                if (actualTypes.length == 0) {
                    result.append("[]");
                } else {
                    result.append("[");
                    if (actualTypes[0] instanceof Class) {
                        Class<?> clz = (Class<?>) actualTypes[0];
                        String s = formatClass1(clz, parents);
                        result.append(s).append("]");
                    } else {
                        result.append("]");
                    }
                }
            }
        } else {
            // 这里需要注意,类的嵌套可能会无限循环,所以引入parents来排除无限嵌套
            if (parents.contains(clazz)) {
                result.append("\"").append(field.getName()).append("\"").append(":").append("{...}");
            } else {
                parents.add(clazz);
                result.append("\"").append(field.getName()).append("\"").append(":")
                        .append(formatClass(clazz, parents));
            }
        }
        if (fields.length != index) {
            result.append(",");
        }
    }
    result.append("}");
    return result.toString();
}
 
Example 19
Project: selenide-appium   File: SelenideAppiumFieldDecorator.java   View Source Code Vote up 4 votes
private Class<?> getListGenericType(Field field) {
  Type genericType = field.getGenericType();
  if (!(genericType instanceof ParameterizedType)) return null;

  return (Class<?>) ((ParameterizedType) genericType).getActualTypeArguments()[0];
}
 
Example 20
Project: jkes   File: ReflectionUtils.java   View Source Code Vote up 3 votes
/**
 * If the field object is a generic type, return innermost type; else return field type name directly
 * @param field Field object
 * @return If the field object is a generic type, return innermost type; else return field type name directly
 */
public static String getInnermostType(Field field) {
    Type type = field.getGenericType();

    String typeName = type.getTypeName(); // ex: java.util.List<com.timeyang.search.entity.Person>, java.lang.Long

    String[] types = typeName.split(",\\s*|<|<|>+");

    return types[types.length - 1];
}