List of usage examples for java.lang Class getDeclaredFields
@CallerSensitive public Field[] getDeclaredFields() throws SecurityException
From source file:ei.ne.ke.cassandra.cql3.EntitySpecificationUtils.java
/** * @param embeddedType//from w w w . j a v a 2 s . com * @return the column mapping of the {@link java.reflect.Field} annotated with * {@link javax.persistence.EmbeddedId}. * * @see http://docs.oracle.com/javaee/6/api/index.html?javax/persistence/EmbeddedId.html */ public static <T> List<String> getCompoundKeyColumnNames(Class<T> embeddedType) { Preconditions.checkNotNull(embeddedType); List<String> columns = Lists.newArrayList(); for (Field embeddedField : embeddedType.getDeclaredFields()) { javax.persistence.Column c = embeddedField.getAnnotation(javax.persistence.Column.class); if (c == null) { continue; } String normalizedName = normalizeCqlElementName(c.name()); if (columns.contains(normalizedName)) { throw new IllegalStateException(String.format("Duplicate column name '%s'", normalizedName)); } columns.add(normalizedName); } for (Method embeddedMethod : embeddedType.getDeclaredMethods()) { javax.persistence.Column c = embeddedMethod.getAnnotation(javax.persistence.Column.class); if (c == null) { continue; } String normalizedName = normalizeCqlElementName(c.name()); if (columns.contains(normalizedName)) { throw new IllegalStateException(String.format("Duplicate column name '%s'", normalizedName)); } columns.add(normalizedName); } return columns; }
From source file:com.autobizlogic.abl.util.BeanUtil.java
private static Field getFieldFromClass(Class<?> cls, String fieldName, Class<?> argClass, boolean onlyProtectedAndHigher) { Field[] allFields = cls.getDeclaredFields(); for (Field field : allFields) { if (!field.getName().equals(fieldName)) continue; int modifiers = field.getModifiers(); if (onlyProtectedAndHigher && Modifier.isPrivate(modifiers)) continue; if (argClass != null) { Class<?> genericType = getGenericType(field.getType()); if (!genericType.isAssignableFrom(argClass)) { String extraInfo = ""; // If the two classes have the same name, it's probably a classloader problem, // so we generate more informative output to help debug if (field.getType().getName().equals(argClass.getName())) { extraInfo = ". It looks like the two classes have the same name, so this is " + "probably a classloader issue. The bean field's class comes from " + field.getType().getClassLoader() + ", the other class comes from " + argClass.getClassLoader(); }//from w ww .jav a 2 s. c om throw new RuntimeException("Bean field " + fieldName + " of class " + cls.getName() + " is of the wrong type (" + field.getType().getName() + ") for the given argument, " + "which is of type " + argClass.getName() + extraInfo); } } return field; } return null; }
From source file:com.greenline.hrs.admin.cache.redis.util.RedisInfoParser.java
/** * RedisInfoMapT?RedisInfoMapRedis?/* w ww . j a v a 2 s . co m*/ * RedisServerInfoPO * * @param instanceType class * @param redisInfoMap Map * @param <T> * @return instanceTypeinfomapnullinfoMap?instancenullRedisServerInfoPO */ public static <T> T parserRedisInfo(Class<T> instanceType, Map<String, String> redisInfoMap) { if (instanceType == null || redisInfoMap == null || redisInfoMap.isEmpty()) { return null; } T instance = null; try { instance = instanceType.newInstance(); } catch (Exception e) { LOG.error("Instance:" + instanceType.getName(), e); return null; } Field[] fields = instanceType.getDeclaredFields(); String inputName = null; for (Field field : fields) { ParserField parserField = field.getAnnotation(ParserField.class); if (parserField != null) { inputName = parserField.inputName(); } else { inputName = field.getName(); } if (redisInfoMap.containsKey(inputName)) { field.setAccessible(true); try { field.set(instance, ConvertUtils.convert(redisInfoMap.get(inputName), field.getType())); } catch (Exception e) { LOG.error("Field:" + field.getName() + "\t|\t value:" + redisInfoMap.get(inputName), e); } } } return instance; }
From source file:cop.raml.mocks.MockUtils.java
private static TypeElementMock createClassElement(@NotNull Class<?> cls) throws ClassNotFoundException { TypeElementMock element = new TypeElementMock(cls.getName(), ElementKind.CLASS); element.setType(new TypeMirrorMock(element, TypeMirrorMock.getTypeKind(cls))); if (cls.getName().startsWith("cop.") || cls.getName().startsWith("spring.")) { VariableElementMock var; for (Field field : cls.getDeclaredFields()) if ((var = createVariable(field.getName(), field.getType(), Modifier.isStatic(field.getModifiers()))) != null) element.addEnclosedElement(setAnnotations(var, field)); ExecutableElementMock exe;//from w w w. ja va 2s . c o m for (Method method : cls.getDeclaredMethods()) if ((exe = createExecutable(method)) != null) element.addEnclosedElement(setAnnotations(exe, method)); } return setAnnotations(element, cls); }
From source file:com.google.gdt.eclipse.designer.ie.util.ReflectionUtils.java
/** * @return the {@link Field} of given class with given name or <code>null</code> if no such {@link Field} * found.// ww w .j av a2 s .co m */ public static Field getFieldByName(Class<?> clazz, String name) { Assert.isNotNull(clazz); Assert.isNotNull(name); // check fields of given class and its super classes while (clazz != null) { // check all declared field Field[] declaredFields = clazz.getDeclaredFields(); for (Field field : declaredFields) { if (field.getName().equals(name)) { field.setAccessible(true); return field; } } // check interfaces { Class<?>[] interfaceClasses = clazz.getInterfaces(); for (Class<?> interfaceClass : interfaceClasses) { Field field = getFieldByName(interfaceClass, name); if (field != null) { return field; } } } // check superclass clazz = clazz.getSuperclass(); } // not found return null; }
From source file:com.qingstor.sdk.utils.QSJSONUtil.java
public static boolean jsonObjFillValue2Object(JSONObject o, Object targetObj) { boolean hasParam = false; if (targetObj != null) { try {//from ww w .j a va2 s . com Class tmpClass = targetObj.getClass(); while (tmpClass != Object.class) { Field[] fields = tmpClass.getDeclaredFields(); if (initParameter(o, fields, tmpClass, targetObj)) { hasParam = true; } tmpClass = tmpClass.getSuperclass(); } } catch (Exception e) { e.printStackTrace(); } } return hasParam; }
From source file:com.ery.ertc.estorm.util.ClassSize.java
/** * The estimate of the size of a class instance depends on whether the JVM uses 32 or 64 bit addresses, that is it depends on the size * of an object reference. It is a linear function of the size of a reference, e.g. 24 + 5*r where r is the size of a reference (usually * 4 or 8 bytes).//ww w .ja v a2 s .c o m * * This method returns the coefficients of the linear function, e.g. {24, 5} in the above example. * * @param cl * A class whose instance size is to be estimated * @param debug * debug flag * @return an array of 3 integers. The first integer is the size of the primitives, the second the number of arrays and the third the * number of references. */ @SuppressWarnings("unchecked") private static int[] getSizeCoefficients(Class cl, boolean debug) { int primitives = 0; int arrays = 0; // The number of references that a new object takes int references = nrOfRefsPerObj; int index = 0; for (; null != cl; cl = cl.getSuperclass()) { Field[] field = cl.getDeclaredFields(); if (null != field) { for (Field aField : field) { if (Modifier.isStatic(aField.getModifiers())) continue; Class fieldClass = aField.getType(); if (fieldClass.isArray()) { arrays++; references++; } else if (!fieldClass.isPrimitive()) { references++; } else {// Is simple primitive String name = fieldClass.getName(); if (name.equals("int") || name.equals("I")) primitives += Bytes.SIZEOF_INT; else if (name.equals("long") || name.equals("J")) primitives += Bytes.SIZEOF_LONG; else if (name.equals("boolean") || name.equals("Z")) primitives += Bytes.SIZEOF_BOOLEAN; else if (name.equals("short") || name.equals("S")) primitives += Bytes.SIZEOF_SHORT; else if (name.equals("byte") || name.equals("B")) primitives += Bytes.SIZEOF_BYTE; else if (name.equals("char") || name.equals("C")) primitives += Bytes.SIZEOF_CHAR; else if (name.equals("float") || name.equals("F")) primitives += Bytes.SIZEOF_FLOAT; else if (name.equals("double") || name.equals("D")) primitives += Bytes.SIZEOF_DOUBLE; } if (debug) { if (LOG.isDebugEnabled()) { LOG.debug("" + index + " " + aField.getName() + " " + aField.getType()); } } index++; } } } return new int[] { primitives, arrays, references }; }
From source file:com.pmarlen.model.controller.EntityJPAToPlainPojoTransformer.java
public static void copyPlainValues(Entity entity, Object plain) { final Class entityClass; entityClass = entity.getClass();/*from w ww . jav a 2 s . c om*/ final String entityClassName = entityClass.getName(); Hashtable<String, Object> propertiesToCopy = new Hashtable<String, Object>(); Hashtable<String, Object> propertiesM2MToCopy = new Hashtable<String, Object>(); List<String> propertiesWithNULLValueToCopy = new ArrayList<String>(); List<String> propertiesKey = new ArrayList<String>(); try { final Field[] declaredFields = entityClass.getDeclaredFields(); for (Field f : declaredFields) { logger.trace("->create: \tcopy: " + entityClassName + "." + f.getName() + " accesible ? " + (f.isAccessible())); if (!f.isAccessible()) { if (f.isAnnotationPresent(javax.persistence.Id.class)) { propertiesKey.add(f.getName()); } if (f.isAnnotationPresent(javax.persistence.Id.class) && !f.isAnnotationPresent(javax.persistence.GeneratedValue.class) && !Modifier.isStatic(f.getModifiers())) { Object valueCopyed = PropertyUtils.getProperty(entity, f.getName()); if (valueCopyed != null) { propertiesToCopy.put(f.getName(), valueCopyed); } else { propertiesWithNULLValueToCopy.add(f.getName()); } logger.trace("->create:\t\t ID elegible 2 be copied, added to copy list: " + f.getName() + " = " + valueCopyed + ", is really null?" + (valueCopyed == null)); } else if (!f.isAnnotationPresent(javax.persistence.Id.class) && !f.isAnnotationPresent(javax.persistence.OneToMany.class) && !f.isAnnotationPresent(javax.persistence.ManyToMany.class) && !Modifier.isStatic(f.getModifiers())) { Object valueCopyed = PropertyUtils.getProperty(entity, f.getName()); if (valueCopyed != null) { propertiesToCopy.put(f.getName(), valueCopyed); } else { propertiesWithNULLValueToCopy.add(f.getName()); } logger.trace("->create:\t\t elegible 2 be copied, added to copy list: " + f.getName() + " = " + valueCopyed + ", is really null?" + (valueCopyed == null)); } else if (!f.isAnnotationPresent(javax.persistence.Id.class) && f.isAnnotationPresent(javax.persistence.ManyToMany.class)) { Object valueCopyed = PropertyUtils.getProperty(entity, f.getName()); if (valueCopyed != null) { propertiesM2MToCopy.put(f.getName(), valueCopyed); } else { propertiesWithNULLValueToCopy.add(f.getName()); } logger.trace("->create:\t\t M2M elegible 2 be copied, added to copy list: " + f.getName() + " = " + valueCopyed + ", is really null?" + (valueCopyed == null)); } } } logger.trace("->create:copy values ?"); for (String p2c : propertiesToCopy.keySet()) { Object valueCopyed = propertiesToCopy.get(p2c); logger.trace("->create:\t\t copy value with SpringUtils: " + p2c + " = " + valueCopyed + ", is null?" + (valueCopyed == null)); BeanUtils.copyProperty(plain, p2c, valueCopyed); } for (String p2c : propertiesWithNULLValueToCopy) { logger.trace("->create:\t\t copy null with SpringUtils"); BeanUtils.copyProperty(plain, p2c, null); } } catch (Exception e) { logger.error("..in copy", e); } }
From source file:ei.ne.ke.cassandra.cql3.EntitySpecificationUtils.java
/** * Constructs a map of {@link String}S representing column names to {@link * Field}S./*from ww w. j a v a 2 s . c om*/ * * @param entityClazz * @return */ public static <T> Map<String, AttributeAccessor> createAccessors(Class<T> entityClazz) { Preconditions.checkNotNull(entityClazz); Map<String, AttributeAccessor> map = Maps.newLinkedHashMap(); for (Field f : entityClazz.getDeclaredFields()) { javax.persistence.Column c = f.getAnnotation(javax.persistence.Column.class); if (c == null) { continue; } String normalizedName = normalizeCqlElementName(c.name()); if (map.containsKey(normalizedName)) { throw new IllegalStateException(String.format("Duplicate column name '%s'", normalizedName)); } AttributeAccessor accessor = new AttributeAccessorFieldIntrospection(f); map.put(normalizedName, accessor); } for (Method firstMethod : entityClazz.getDeclaredMethods()) { javax.persistence.Column c = firstMethod.getAnnotation(javax.persistence.Column.class); if (c == null) { continue; } String normalizedName = normalizeCqlElementName(c.name()); /* * For bean getters and setters, we allow to annotate either the * getter or the setter and will find the corresponding counterpart. * If the column name is already mapped, then there's either a * @Column-annotated field, or the previous reversed pair of getters * and setters was found. Either way, ignore this annotated method. */ if (map.containsKey(normalizedName)) { continue; } String firstMethodName = firstMethod.getName(); AttributeAccessor accessor = null; if (firstMethodName.startsWith("set")) { String attributeName = firstMethodName.substring(NON_BOOLEAN_BEAN_PROPERTY_ACCESSOR_PREFIX_LENGTH); Method secondMethod = findGetterMethod(entityClazz, attributeName); if (secondMethod == null) { throw new IllegalArgumentException(String.format("No counterpart to %s", firstMethodName)); } accessor = new AttributeAccessorBeanMethods(secondMethod, firstMethod); } else if (firstMethodName.startsWith("is")) { String attributeName = firstMethodName.substring(BOOLEAN_BEAN_PROPERTY_ACCESSOR_PREFIX_LENGTH); Method secondMethod = findSetterMethod(entityClazz, attributeName); if (secondMethod == null) { throw new IllegalArgumentException(String.format("No counterpart to %s", firstMethodName)); } accessor = new AttributeAccessorBeanMethods(firstMethod, secondMethod); } else if (firstMethodName.startsWith("get")) { String attributeName = firstMethodName.substring(NON_BOOLEAN_BEAN_PROPERTY_ACCESSOR_PREFIX_LENGTH); /* * Find the corresponding setter. */ Method secondMethod = findSetterMethod(entityClazz, attributeName); if (secondMethod == null) { throw new IllegalArgumentException(String.format("No counterpart to %s", firstMethodName)); } accessor = new AttributeAccessorBeanMethods(firstMethod, secondMethod); } map.put(normalizedName, accessor); } return map; }
From source file:com.impetus.kundera.utils.KunderaCoreUtils.java
public static int countNonSyntheticFields(Class<?> clazz) { int count = 0; for (Field f : clazz.getDeclaredFields()) { if (!f.isSynthetic() || !ReflectUtils.isTransientOrStatic(f)) { count++;/*from w ww . j av a 2s .com*/ } } return count; }