List of usage examples for java.lang.reflect Field getGenericType
public Type getGenericType()
From source file:org.jenkinsci.plugins.workflow.structs.DescribableHelper.java
private static Object inspect(Object o, Class<?> clazz, String field, AtomicReference<Type> type) { try {/*w ww. jav a 2 s .co m*/ try { Field f = clazz.getField(field); type.set(f.getGenericType()); return f.get(o); } catch (NoSuchFieldException x) { // OK, check for getter instead } try { Method m = clazz.getMethod("get" + Character.toUpperCase(field.charAt(0)) + field.substring(1)); type.set(m.getGenericReturnType()); return m.invoke(o); } catch (NoSuchMethodException x) { // one more check } try { type.set(boolean.class); return clazz.getMethod("is" + Character.toUpperCase(field.charAt(0)) + field.substring(1)) .invoke(o); } catch (NoSuchMethodException x) { throw new UnsupportedOperationException( "no public field " + field + " (or getter method) found in " + clazz); } } catch (UnsupportedOperationException x) { throw x; } catch (Exception x) { throw new UnsupportedOperationException(x); } }
From source file:com.stratio.deep.commons.utils.CellsUtils.java
/** * Gets object from json./* w ww .j a v a 2 s . c o m*/ * * @param classEntity the class entity * @param bsonObject the bson object * @return the object from json * @throws IllegalAccessException the illegal access exception * @throws InstantiationException the instantiation exception * @throws InvocationTargetException the invocation target exception */ public static <T> T getObjectFromJson(Class<T> classEntity, JSONObject bsonObject) throws IllegalAccessException, InstantiationException, InvocationTargetException { T t = classEntity.newInstance(); Field[] fields = AnnotationUtils.filterDeepFields(classEntity); Object insert = null; for (Field field : fields) { Object currentBson = null; Method method = null; try { method = Utils.findSetter(field.getName(), classEntity, field.getType()); Class<?> classField = field.getType(); currentBson = bsonObject.get(AnnotationUtils.deepFieldName(field)); if (currentBson != null) { if (Iterable.class.isAssignableFrom(classField)) { Type type = field.getGenericType(); insert = subDocumentListCase(type, (List) bsonObject.get(AnnotationUtils.deepFieldName(field))); } else if (IDeepType.class.isAssignableFrom(classField)) { insert = getObjectFromJson(classField, (JSONObject) bsonObject.get(AnnotationUtils.deepFieldName(field))); } else { insert = currentBson; } method.invoke(t, insert); } } catch (IllegalAccessException | InstantiationException | InvocationTargetException | IllegalArgumentException e) { LOG.error("impossible to create a java object from Bson field:" + field.getName() + " and type:" + field.getType() + " and value:" + t + "; bsonReceived:" + currentBson + ", bsonClassReceived:" + currentBson.getClass()); method.invoke(t, Utils.castNumberType(insert, t.getClass())); } } return t; }
From source file:org.tdar.core.service.ReflectionService.java
/** * Get the return type of a field/*from w ww .j a v a2 s . c o m*/ * * @param accessibleObject * @return */ public static Class<?> getFieldReturnType(AccessibleObject accessibleObject) { final Logger log = LoggerFactory.getLogger(ReflectionService.class); if (accessibleObject instanceof Field) { Field field = (Field) accessibleObject; log.trace("generic type: {}", field.getGenericType()); return getType(field.getGenericType()); } if (accessibleObject instanceof Method) { Method method = (Method) accessibleObject; log.trace("generic type: {}", method.getGenericReturnType()); return getType(method.getGenericReturnType()); } return null; }
From source file:com.stratio.deep.commons.utils.CellsUtils.java
public static <T> T getObjectWithMapFromJson(Class<T> classEntity, JSONObject bsonObject) throws IllegalAccessException, InstantiationException, InvocationTargetException { T t = classEntity.newInstance();/* w ww. j ava 2s .com*/ Field[] fields = AnnotationUtils.filterDeepFields(classEntity); Object insert = null; for (Field field : fields) { Object currentBson = null; Method method = null; try { method = Utils.findSetter(field.getName(), classEntity, field.getType()); Class<?> classField = field.getType(); currentBson = bsonObject.get(AnnotationUtils.deepFieldName(field)); if (currentBson != null) { if (Collection.class.isAssignableFrom(classField)) { Type type = field.getGenericType(); List list = new ArrayList(); for (Object o : (List) bsonObject.get(AnnotationUtils.deepFieldName(field))) { list.add((String) o); } insert = list; } else if (IDeepType.class.isAssignableFrom(classField)) { insert = getObjectFromJson(classField, (JSONObject) bsonObject.get(AnnotationUtils.deepFieldName(field))); } else { insert = currentBson; } if (insert != null) { method.invoke(t, insert); } } } catch (IllegalAccessException | InstantiationException | InvocationTargetException | IllegalArgumentException e) { LOG.error("impossible to create a java object from Bson field:" + field.getName() + " and type:" + field.getType() + " and value:" + t + "; bsonReceived:" + currentBson + ", bsonClassReceived:" + currentBson.getClass()); method.invoke(t, Utils.castNumberType(insert, t.getClass())); } } return t; }
From source file:com.stratio.deep.es.utils.UtilES.java
/** * converts from JSONObject to an entity class with deep's anotations * * @param classEntity the entity name./*from w w w. j a v a 2 s .c o m*/ * @param jsonObject the instance of the JSONObject to convert. * @param <T> return type. * @return the provided JSONObject converted to an instance of T. * @throws IllegalAccessException * @throws InstantiationException * @throws java.lang.reflect.InvocationTargetException */ public static <T> T getObjectFromJson(Class<T> classEntity, LinkedMapWritable jsonObject) throws IllegalAccessException, InstantiationException, InvocationTargetException, NoSuchMethodException { T t = classEntity.newInstance(); Field[] fields = AnnotationUtils.filterDeepFields(classEntity); Object insert; for (Field field : fields) { Method method = Utils.findSetter(field.getName(), classEntity, field.getType()); Class<?> classField = field.getType(); String key = AnnotationUtils.deepFieldName(field); Text text = new org.apache.hadoop.io.Text(key); Writable currentJson = jsonObject.get(text); if (currentJson != null) { if (Iterable.class.isAssignableFrom(classField)) { Type type = field.getGenericType(); insert = subDocumentListCase(type, (ArrayWritable) currentJson); method.invoke(t, (insert)); } else if (IDeepType.class.isAssignableFrom(classField)) { insert = getObjectFromJson(classField, (LinkedMapWritable) currentJson); method.invoke(t, (insert)); } else { insert = currentJson; try { method.invoke(t, getObjectFromWritable((Writable) insert)); } catch (Exception e) { LOG.error("impossible to convert field " + t + " :" + field + " error: " + e.getMessage()); method.invoke(t, Utils.castNumberType(getObjectFromWritable((Writable) insert), t.getClass())); } } } } return t; }
From source file:com.qingstor.sdk.utils.QSJSONUtil.java
private static void setParameterToMap(Method m, Object source, Field f, Object data) { if (data != null) { try {//ww w . j a v a 2 s . c o m if (data instanceof JSONArray || data instanceof JSONObject) { Class fClass = f.getType(); if (fClass.equals(List.class)) { List invokeData = new ArrayList(); ParameterizedType stringListType = (ParameterizedType) f.getGenericType(); Class<?> cls = (Class<?>) stringListType.getActualTypeArguments()[0]; if (cls.equals(String.class) || cls.equals(Integer.class) || cls.equals(Double.class) || cls.equals(Long.class) || cls.equals(Float.class)) { if (data instanceof JSONArray) { JSONArray jsonData = (JSONArray) data; for (int i = 0; i < jsonData.length(); i++) { Object o = toObject(jsonData, i); invokeData.add(o); } } } else { if (data instanceof JSONArray) { JSONArray jsonData = (JSONArray) data; for (int i = 0; i < jsonData.length(); i++) { Object fObject = cls.newInstance(); JSONObject o = toJSONObject(jsonData, i); Class tmpClass = fObject.getClass(); while (tmpClass != Object.class) { Field[] fields = tmpClass.getDeclaredFields(); initParameter(o, fields, tmpClass, fObject); tmpClass = tmpClass.getSuperclass(); } invokeData.add(fObject); } } } m.invoke(source, invokeData); } else if (fClass.equals(Map.class)) { Map invokeData = new HashMap(); if (data instanceof JSONObject) { JSONObject jsonData = (JSONObject) data; for (int i = 0; i < jsonData.length(); i++) { String key = toJSONObject(jsonData, i) + ""; Object value = toJSONObject(jsonData, key); invokeData.put(key, value); } } m.invoke(source, invokeData); } else { Object invokeData = f.getType().newInstance(); Class tmpClass = invokeData.getClass(); while (tmpClass != Object.class) { Field[] fields = tmpClass.getDeclaredFields(); initParameter((JSONObject) data, fields, tmpClass, invokeData); tmpClass = tmpClass.getSuperclass(); } m.invoke(source, invokeData); } } else { if (f.getType().equals(data.getClass())) { m.invoke(source, data); } else { m.invoke(source, getParseValue(f.getType(), data)); } } } catch (Exception e) { e.printStackTrace(); } } }
From source file:com.android.camera2.its.ItsSerializer.java
@SuppressWarnings("unchecked") public static CaptureRequest.Builder deserialize(CaptureRequest.Builder mdDefault, JSONObject jsonReq) throws ItsException { try {/*w ww . j a v a 2 s .c o m*/ Logt.i(TAG, "Parsing JSON capture request ..."); // Iterate over the CaptureRequest reflected fields. CaptureRequest.Builder md = mdDefault; Field[] allFields = CaptureRequest.class.getDeclaredFields(); for (Field field : allFields) { if (Modifier.isPublic(field.getModifiers()) && Modifier.isStatic(field.getModifiers()) && field.getType() == CaptureRequest.Key.class && field.getGenericType() instanceof ParameterizedType) { ParameterizedType paramType = (ParameterizedType) field.getGenericType(); Type[] argTypes = paramType.getActualTypeArguments(); if (argTypes.length > 0) { CaptureRequest.Key key = (CaptureRequest.Key) field.get(md); String keyName = key.getName(); Type keyType = argTypes[0]; // For each reflected CaptureRequest entry, look inside the JSON object // to see if it is being set. If it is found, remove the key from the // JSON object. After this process, there should be no keys left in the // JSON (otherwise an invalid key was specified). if (jsonReq.has(keyName) && !jsonReq.isNull(keyName)) { if (keyType instanceof GenericArrayType) { Type elmtType = ((GenericArrayType) keyType).getGenericComponentType(); JSONArray ja = jsonReq.getJSONArray(keyName); Object val[] = new Object[ja.length()]; for (int i = 0; i < ja.length(); i++) { if (elmtType == int.class) { Array.set(val, i, ja.getInt(i)); } else if (elmtType == byte.class) { Array.set(val, i, (byte) ja.getInt(i)); } else if (elmtType == float.class) { Array.set(val, i, (float) ja.getDouble(i)); } else if (elmtType == long.class) { Array.set(val, i, ja.getLong(i)); } else if (elmtType == double.class) { Array.set(val, i, ja.getDouble(i)); } else if (elmtType == boolean.class) { Array.set(val, i, ja.getBoolean(i)); } else if (elmtType == String.class) { Array.set(val, i, ja.getString(i)); } else if (elmtType == Size.class) { JSONObject obj = ja.getJSONObject(i); Array.set(val, i, new Size(obj.getInt("width"), obj.getInt("height"))); } else if (elmtType == Rect.class) { JSONObject obj = ja.getJSONObject(i); Array.set(val, i, new Rect(obj.getInt("left"), obj.getInt("top"), obj.getInt("bottom"), obj.getInt("right"))); } else if (elmtType == Rational.class) { JSONObject obj = ja.getJSONObject(i); Array.set(val, i, new Rational(obj.getInt("numerator"), obj.getInt("denominator"))); } else if (elmtType == RggbChannelVector.class) { JSONArray arr = ja.getJSONArray(i); Array.set(val, i, new RggbChannelVector((float) arr.getDouble(0), (float) arr.getDouble(1), (float) arr.getDouble(2), (float) arr.getDouble(3))); } else if (elmtType == ColorSpaceTransform.class) { JSONArray arr = ja.getJSONArray(i); Rational xform[] = new Rational[9]; for (int j = 0; j < 9; j++) { xform[j] = new Rational(arr.getJSONObject(j).getInt("numerator"), arr.getJSONObject(j).getInt("denominator")); } Array.set(val, i, new ColorSpaceTransform(xform)); } else if (elmtType == MeteringRectangle.class) { JSONObject obj = ja.getJSONObject(i); Array.set(val, i, new MeteringRectangle(obj.getInt("x"), obj.getInt("y"), obj.getInt("width"), obj.getInt("height"), obj.getInt("weight"))); } else { throw new ItsException("Failed to parse key from JSON: " + keyName); } } if (val != null) { Logt.i(TAG, "Set: " + keyName + " -> " + Arrays.toString(val)); md.set(key, val); jsonReq.remove(keyName); } } else { Object val = null; if (keyType == Integer.class) { val = jsonReq.getInt(keyName); } else if (keyType == Byte.class) { val = (byte) jsonReq.getInt(keyName); } else if (keyType == Double.class) { val = jsonReq.getDouble(keyName); } else if (keyType == Long.class) { val = jsonReq.getLong(keyName); } else if (keyType == Float.class) { val = (float) jsonReq.getDouble(keyName); } else if (keyType == Boolean.class) { val = jsonReq.getBoolean(keyName); } else if (keyType == String.class) { val = jsonReq.getString(keyName); } else if (keyType == Size.class) { JSONObject obj = jsonReq.getJSONObject(keyName); val = new Size(obj.getInt("width"), obj.getInt("height")); } else if (keyType == Rect.class) { JSONObject obj = jsonReq.getJSONObject(keyName); val = new Rect(obj.getInt("left"), obj.getInt("top"), obj.getInt("right"), obj.getInt("bottom")); } else if (keyType == Rational.class) { JSONObject obj = jsonReq.getJSONObject(keyName); val = new Rational(obj.getInt("numerator"), obj.getInt("denominator")); } else if (keyType == RggbChannelVector.class) { JSONObject obj = jsonReq.optJSONObject(keyName); JSONArray arr = jsonReq.optJSONArray(keyName); if (arr != null) { val = new RggbChannelVector((float) arr.getDouble(0), (float) arr.getDouble(1), (float) arr.getDouble(2), (float) arr.getDouble(3)); } else if (obj != null) { val = new RggbChannelVector((float) obj.getDouble("red"), (float) obj.getDouble("greenEven"), (float) obj.getDouble("greenOdd"), (float) obj.getDouble("blue")); } else { throw new ItsException("Invalid RggbChannelVector object"); } } else if (keyType == ColorSpaceTransform.class) { JSONArray arr = jsonReq.getJSONArray(keyName); Rational a[] = new Rational[9]; for (int i = 0; i < 9; i++) { a[i] = new Rational(arr.getJSONObject(i).getInt("numerator"), arr.getJSONObject(i).getInt("denominator")); } val = new ColorSpaceTransform(a); } else if (keyType instanceof ParameterizedType && ((ParameterizedType) keyType).getRawType() == Range.class && ((ParameterizedType) keyType).getActualTypeArguments().length == 1 && ((ParameterizedType) keyType) .getActualTypeArguments()[0] == Integer.class) { JSONArray arr = jsonReq.getJSONArray(keyName); val = new Range<Integer>(arr.getInt(0), arr.getInt(1)); } else { throw new ItsException( "Failed to parse key from JSON: " + keyName + ", " + keyType); } if (val != null) { Logt.i(TAG, "Set: " + keyName + " -> " + val); md.set(key, val); jsonReq.remove(keyName); } } } } } } // Ensure that there were no invalid keys in the JSON request object. if (jsonReq.length() != 0) { throw new ItsException("Invalid JSON key(s): " + jsonReq.toString()); } Logt.i(TAG, "Parsing JSON capture request completed"); return md; } catch (java.lang.IllegalAccessException e) { throw new ItsException("Access error: ", e); } catch (org.json.JSONException e) { throw new ItsException("JSON error: ", e); } }
From source file:org.vulpe.commons.util.VulpeReflectUtil.java
public static Class<?> getFieldClass(final Class<?> clazz, final String fieldName) { final Field field = getField(clazz, fieldName); return field == null ? null : getDeclaredType(clazz, field.getGenericType()).getType(); }
From source file:me.xiaopan.android.gohttp.requestobject.RequestParser.java
/** * ?typecollectionType?collectionType=List.classtype=Date.class??DateList *///from w w w .j av a2s . c o m @SuppressWarnings("rawtypes") private static boolean isCollectionByType(Field field, Class<? extends Collection> collectionType, Class<?> type) { Class<?> fieldType = field.getType(); if (collectionType.isAssignableFrom(fieldType)) { Class<?> first = (Class<?>) ((ParameterizedType) field.getGenericType()).getActualTypeArguments()[0]; return type.isAssignableFrom(first); } else { return false; } }
From source file:com.android.camera2.its.ItsSerializer.java
@SuppressWarnings("unchecked") public static JSONObject serialize(CameraMetadata md) throws ItsException { JSONObject jsonObj = new JSONObject(); Field[] allFields = md.getClass().getDeclaredFields(); if (md.getClass() == TotalCaptureResult.class) { allFields = CaptureResult.class.getDeclaredFields(); }//from w w w . java 2 s.c o m for (Field field : allFields) { if (Modifier.isPublic(field.getModifiers()) && Modifier.isStatic(field.getModifiers()) && (field.getType() == CaptureRequest.Key.class || field.getType() == CaptureResult.Key.class || field.getType() == TotalCaptureResult.Key.class || field.getType() == CameraCharacteristics.Key.class) && field.getGenericType() instanceof ParameterizedType) { ParameterizedType paramType = (ParameterizedType) field.getGenericType(); Type[] argTypes = paramType.getActualTypeArguments(); if (argTypes.length > 0) { try { Type keyType = argTypes[0]; Object keyObj = field.get(md); MetadataEntry entry; if (keyType instanceof GenericArrayType) { entry = serializeArrayEntry(keyType, keyObj, md); } else { entry = serializeEntry(keyType, keyObj, md); } // TODO: Figure this weird case out. // There is a weird case where the entry is non-null but the toString // of the entry is null, and if this happens, the null-ness spreads like // a virus and makes the whole JSON object null from the top level down. // Not sure if it's a bug in the library or I'm just not using it right. // Workaround by checking for this case explicitly and not adding the // value to the jsonObj when it is detected. if (entry != null && entry.key != null && entry.value != null && entry.value.toString() == null) { Logt.w(TAG, "Error encountered serializing value for key: " + entry.key); } else if (entry != null) { jsonObj.put(entry.key, entry.value); } else { // Ignore. } } catch (IllegalAccessException e) { throw new ItsException("Access error for field: " + field + ": ", e); } catch (org.json.JSONException e) { throw new ItsException("JSON error for field: " + field + ": ", e); } } } } return jsonObj; }