List of usage examples for java.lang.reflect Field getType
public Class<?> getType()
From source file:com.stratio.deep.commons.utils.CellsUtils.java
/** * Gets object from json./* w w w .j ava 2 s . c om*/ * * @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: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();/*from w w w .j a va 2 s . c om*/ 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.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 a v a 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:eagle.log.entity.EntityQualifierUtils.java
public static Class<?> getType(EntityDefinition ed, String qualifierName) { Field field; try {// w w w. j a va2 s. c o m field = ed.getEntityClass().getDeclaredField(qualifierName); } catch (NoSuchFieldException e) { if (LOG.isDebugEnabled()) LOG.debug("Field " + qualifierName + " not found in " + ed.getEntityClass()); return null; } return field.getType(); }
From source file:com.belle.infrastructure.util.ReflectionUtils.java
/** * , private/protected, ??setter.//from w w w.j a va 2 s . co m */ public static void setFieldValueByFieldType(final Object object, final String fieldName, final Object value) { Field field = getDeclaredField(object, fieldName); if (field == null) { throw new IllegalArgumentException( "Could not find field [" + fieldName + "] on target [" + object + "]"); } setFieldValue(object, fieldName, convertStringToObject((String) value, field.getType())); }
From source file:com.abiquo.model.util.ModelTransformer.java
public static <T> void transform(final Class sourceClass, final Class<T> targetClass, final Object source, final T target) throws Exception { Field[] transportFields = sourceClass.getDeclaredFields(); Class superClass = sourceClass.getSuperclass(); while (!superClass.getSimpleName().equalsIgnoreCase("SingleResourceTransportDto")) { transportFields = (Field[]) ArrayUtils.addAll(transportFields, superClass.getDeclaredFields()); superClass = superClass.getSuperclass(); }//from www . ja va 2 s. c o m for (Field field : transportFields) { int modifiers = field.getModifiers(); if (!Modifier.isTransient(modifiers) && !Modifier.isStatic(modifiers)) { String name = field.getName(); try { if (fieldExist(name, targetClass) && fieldExist(name, source.getClass()) || getterExist(name, source.getClass()) && setterExist(name, targetClass, field.getType())) { Object value = getter(name, source.getClass()).invoke(source, new Object[0]); if (setterExist(name, targetClass, field.getType())) { setter(name, targetClass, field.getType()).invoke(target, new Object[] { value }); } } } catch (InvocationTargetException e) { // Ignore invalid field } } } }
From source file:com.cloud.api.ApiDispatcher.java
public static void plugService(Field field, BaseCmd cmd) { Class<?> fc = field.getType(); Object instance = null;/*from w ww . j av a2 s .c o m*/ if (instance == null) { throw new CloudRuntimeException("Unable to plug service " + fc.getSimpleName() + " in command " + cmd.getClass().getSimpleName()); } try { field.setAccessible(true); field.set(cmd, instance); } catch (IllegalArgumentException e) { s_logger.error("IllegalArgumentException at plugService for command " + cmd.getCommandName() + ", field " + field.getName()); throw new CloudRuntimeException("Internal error at plugService for command " + cmd.getCommandName() + " [Illegal argumet at field " + field.getName() + "]"); } catch (IllegalAccessException e) { s_logger.error("Error at plugService for command " + cmd.getCommandName() + ", field " + field.getName() + " is not accessible."); throw new CloudRuntimeException("Internal error at plugService for command " + cmd.getCommandName() + " [field " + field.getName() + " is not accessible]"); } }
From source file:Main.java
public static boolean overrideClassLoader(ClassLoader cl, File dex, File opt) { try {// w w w. ja v a2 s. co m ClassLoader bootstrap = cl.getParent(); Field fPathList = BaseDexClassLoader.class.getDeclaredField("pathList"); fPathList.setAccessible(true); Object pathList = fPathList.get(cl); Class cDexPathList = bootstrap.loadClass("dalvik.system.DexPathList"); Field fDexElements = cDexPathList.getDeclaredField("dexElements"); fDexElements.setAccessible(true); Object dexElements = fDexElements.get(pathList); DexClassLoader cl2 = new DexClassLoader(dex.getAbsolutePath(), opt.getAbsolutePath(), null, bootstrap); Object pathList2 = fPathList.get(cl2); Object dexElements2 = fDexElements.get(pathList2); Object element2 = Array.get(dexElements2, 0); int n = Array.getLength(dexElements) + 1; Object newDexElements = Array.newInstance(fDexElements.getType().getComponentType(), n); Array.set(newDexElements, 0, element2); for (int i = 0; i < n - 1; i++) { Object element = Array.get(dexElements, i); Array.set(newDexElements, i + 1, element); } fDexElements.set(pathList, newDexElements); return true; } catch (Exception e) { Log.e("lcast", "fail to override classloader " + cl + " with " + dex, e); return false; } }
From source file:com.netflix.paas.config.base.ConfigurationProxyUtils.java
static void assignFieldValues(final Object obj, Class<?> type, DynamicPropertyFactory propertyFactory, AbstractConfiguration configuration) throws Exception { // Iterate through all fields and set initial value as well as set up dynamic properties // where necessary for (final Field field : type.getFields()) { Configuration c = field.getAnnotation(Configuration.class); if (c == null) continue; String defaultValue = field.get(obj).toString(); String name = ConfigurationProxyUtils.getPropertyName(field, c); Supplier<?> supplier = ConfigurationProxyUtils.getStaticSupplier(field.getType(), name, defaultValue, configuration);// w w w. jav a 2 s . c om field.set(obj, supplier.get()); if (field.getAnnotation(Dynamic.class) != null) { final PropertyWrapper<?> property; if (field.getType().isAssignableFrom(String.class)) { property = propertyFactory.getStringProperty(name, defaultValue); } else if (field.getType().isAssignableFrom(Integer.class)) { property = propertyFactory.getIntProperty(name, defaultValue == null ? 0 : Integer.parseInt(defaultValue)); } else if (field.getType().isAssignableFrom(Double.class)) { property = propertyFactory.getDoubleProperty(name, defaultValue == null ? 0.0 : Double.parseDouble(defaultValue)); } else if (field.getType().isAssignableFrom(Long.class)) { property = propertyFactory.getLongProperty(name, defaultValue == null ? 0L : Long.parseLong(defaultValue)); } else if (field.getType().isAssignableFrom(Boolean.class)) { property = propertyFactory.getBooleanProperty(name, defaultValue == null ? false : Boolean.parseBoolean(defaultValue)); } else { throw new RuntimeException("Unsupported type " + field.getType()); } property.addCallback(new Runnable() { @Override public void run() { try { field.set(obj, property.getValue()); } catch (Exception e) { e.printStackTrace(); } } }); } } }
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);/* w w w.ja v a2 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); } } } }