public void testImmutable() { Class<Fastq> cls = Fastq.class; assertTrue(Modifier.isPublic(cls.getModifiers())); assertTrue(Modifier.isFinal(cls.getModifiers())); Field[] fields = cls.getDeclaredFields(); for (Field field : fields) { assertTrue(Modifier.isPrivate(field.getModifiers())); assertTrue( Modifier.isFinal(field.getModifiers()) || (Modifier.isVolatile(field.getModifiers()) && Modifier.isTransient(field.getModifiers()))); } }
@Override public final T serializeAs(Object o, Class<?> clazz) throws SerializerException { if (PrimitiveHandler.isPrimitive(o)) { // Problem throw new SerializerException("Asked to serialize primitive instance as a composite object"); } // We get here if the object is not primitive Map<String, T> contents = new HashMap<String, T>(); for (Field field : GenericSerializer.getAllFields(o.getClass())) { // Is this field declared as transient? if (Modifier.isTransient(field.getModifiers())) { // Yes: don't serialize this field continue; } field.setAccessible(true); try { String field_name = field.getName(); Object field_value = field.get(o); Class<?> declared_type = field.getType(); T serialized_value = m_serializer.serializeAs(field_value, declared_type); contents.put(field_name, serialized_value); } catch (IllegalArgumentException e) { throw new SerializerException(e); } catch (IllegalAccessException e) { throw new SerializerException(e); } } return serializeObject(o, contents); }
public List<Model.Property> listProperties() { List<Model.Property> properties = new ArrayList<Model.Property>(); Set<Field> fields = new HashSet<Field>(); Class<?> tclazz = clazz; while (!tclazz.equals(Object.class)) { Collections.addAll(fields, tclazz.getDeclaredFields()); tclazz = tclazz.getSuperclass(); } for (Field f : fields) { if (Modifier.isTransient(f.getModifiers())) { continue; } if (Modifier.isStatic(f.getModifiers())) { continue; } if (f.isAnnotationPresent(Transient.class) && !f.getType().equals(Blob.class)) { continue; } Model.Property mp = buildProperty(f); if (mp != null) { properties.add(mp); } } return properties; }
public void makeValid() { if (getIssuetype() != null) { Class<?> klass = getClass(); while (klass != HashMap.class) { for (Field field : klass.getDeclaredFields()) { if (!getIssuetype().getFields().containsKey(field.getName())) { if (Modifier.isFinal(field.getModifiers()) || Modifier.isStatic(field.getModifiers()) || Modifier.isTransient(field.getModifiers())) { continue; } field.setAccessible(true); try { field.set(this, null); } catch (IllegalArgumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } klass = klass.getSuperclass(); } for (Map.Entry<String, Object> e : new HashMap<String, Object>(this).entrySet()) { if (!getIssuetype().getFields().containsKey(e.getKey())) { this.remove(e.getKey()); } } } }
/** * 是否规定的忽略字段 * * @param f * @return */ public static boolean isIgnoredField(Field f) { int mods = f.getModifiers(); return Modifier.isStatic(mods) || Modifier.isFinal(mods) || Modifier.isTransient(mods) || f.getName().startsWith("this$"); }
private static void reflectionAppend( Object obj, Object obj1, Class class1, CompareToBuilder comparetobuilder, boolean flag, String as[]) { Field afield[] = class1.getDeclaredFields(); AccessibleObject.setAccessible(afield, true); int i = 0; do { if (i >= afield.length || comparetobuilder.comparison != 0) { return; } Field field = afield[i]; if (!ArrayUtils.contains(as, field.getName()) && field.getName().indexOf('$') == -1 && (flag || !Modifier.isTransient(field.getModifiers())) && !Modifier.isStatic(field.getModifiers())) { try { comparetobuilder.append(field.get(obj), field.get(obj1)); } catch (IllegalAccessException illegalaccessexception) { throw new InternalError("Unexpected IllegalAccessException"); } } i++; } while (true); }
private ObjectMap<String, FieldMetadata> cacheFields(Class type) { ArrayList<Field> allFields = new ArrayList(); Class nextClass = type; while (nextClass != Object.class) { Collections.addAll(allFields, nextClass.getDeclaredFields()); nextClass = nextClass.getSuperclass(); } ObjectMap<String, FieldMetadata> nameToField = new ObjectMap(); for (int i = 0, n = allFields.size(); i < n; i++) { Field field = allFields.get(i); int modifiers = field.getModifiers(); if (Modifier.isTransient(modifiers)) continue; if (Modifier.isStatic(modifiers)) continue; if (field.isSynthetic()) continue; if (!field.isAccessible()) { try { field.setAccessible(true); } catch (AccessControlException ex) { continue; } } nameToField.put(field.getName(), new FieldMetadata(field)); } typeToFields.put(type, nameToField); return nameToField; }
public String[] save() { ArrayList<String> lines = new ArrayList<String>(); Field[] fields = getClass().getDeclaredFields(); lines.add("<config>"); for (Field f : fields) { if (isConfigItem(f)) { Object obj; try { f.setAccessible(true); obj = f.get(this); } catch (IllegalAccessException e) { e.printStackTrace(); continue; } if (obj instanceof ConfigParser) { lines.add("<" + f.getName() + ">"); ConfigParser parser = (ConfigParser) obj; parser.save(lines); lines.add("</" + f.getName() + ">"); } else { String item_name = f.getName(); if (!Modifier.isTransient(f.getModifiers())) { lines.add("<" + item_name + ">" + obj.toString() + "</" + item_name + ">"); } } } } lines.add("</config>"); return lines.toArray(new String[lines.size()]); }
public List<Model.Property> listProperties() { List<Model.Property> properties = new ArrayList<Model.Property>(); Set<Field> fields = new LinkedHashSet<Field>(); Class<?> tclazz = clazz; while (!tclazz.equals(Object.class)) { Collections.addAll(fields, tclazz.getDeclaredFields()); tclazz = tclazz.getSuperclass(); } for (Field f : fields) { int mod = f.getModifiers(); if (Modifier.isTransient(mod) || Modifier.isStatic(mod)) { continue; } if (f.isAnnotationPresent(Transient.class)) { continue; } if (f.isAnnotationPresent(NoBinding.class)) { NoBinding a = f.getAnnotation(NoBinding.class); List<String> values = Arrays.asList(a.value()); if (values.contains("*")) { continue; } } Model.Property mp = buildProperty(f); if (mp != null) { properties.add(mp); } } return properties; }
/** * Applications which override this can do custom serialization. * * @param object the object to write. */ public void writeObjectImpl(Object obj) throws IOException { Class cl = obj.getClass(); try { Method method = cl.getMethod("writeReplace", new Class[0]); Object repl = method.invoke(obj, new Object[0]); writeObject(repl); return; } catch (Exception e) { } try { writeMapBegin(cl.getName()); for (; cl != null; cl = cl.getSuperclass()) { Field[] fields = cl.getDeclaredFields(); for (int i = 0; i < fields.length; i++) { Field field = fields[i]; if (Modifier.isTransient(field.getModifiers()) || Modifier.isStatic(field.getModifiers())) continue; // XXX: could parameterize the handler to only deal with public field.setAccessible(true); writeString(field.getName()); writeObject(field.get(obj)); } } writeMapEnd(); } catch (IllegalAccessException e) { throw new IOExceptionWrapper(e); } }
public String process() { if (this.type.getCanonicalName() == null) { // new RuntimeException( "Ignoring anonymous class: " + this.type // ).printStackTrace( ); } else { this.elem(Elem.mapping); if (this.abs) { this.attr("abstract", "true"); } else { this.attr("name", this.type.getSimpleName()) .attr("extends", this.type.getSuperclass().getCanonicalName()); } this.attr("class", this.type.getCanonicalName()); if (BindingFileSearch.INSTANCE.MSG_BASE_CLASS.isAssignableFrom(this.type.getSuperclass()) || BindingFileSearch.INSTANCE.MSG_DATA_CLASS.isAssignableFrom( this.type.getSuperclass())) { this.elem(Elem.structure) .attr("map-as", this.type.getSuperclass().getCanonicalName()) .end(); } for (Field f : this.type.getDeclaredFields()) { if (!Ats.from(f).has(Transient.class) || Modifier.isTransient(f.getModifiers())) { TypeBinding tb = getTypeBinding(f); if (!(tb instanceof NoopTypeBinding)) { // System.out.printf( "BOUND: %-70s [type=%s:%s]\n", // f.getDeclaringClass( ).getCanonicalName( ) +"."+ f.getName( ), tb.getTypeName( ), // f.getType( ).getCanonicalName( ) ); this.append(tb.toString()); } } } this.end(); } return this.toString(); }
/** * Appends the fields and values defined by the given object of the given Class. * * @param lhs the left hand object * @param rhs the right hand object * @param clazz the class to append details of * @param builder the builder to append to * @param useTransients whether to test transient fields * @param excludeFields array of field names to exclude from testing */ private static void reflectionAppend( Object lhs, Object rhs, Class<?> clazz, EqualsBuilder builder, boolean useTransients, String[] excludeFields) { if (isRegistered(lhs, rhs)) { return; } try { register(lhs, rhs); Field[] fields = clazz.getDeclaredFields(); AccessibleObject.setAccessible(fields, true); for (int i = 0; i < fields.length && builder.isEquals; i++) { Field f = fields[i]; if (!Arrays.contains(excludeFields, f.getName()) && (f.getName().indexOf('$') == -1) && (useTransients || !Modifier.isTransient(f.getModifiers())) && (!Modifier.isStatic(f.getModifiers()))) { try { builder.append(f.get(lhs), f.get(rhs)); } catch (IllegalAccessException e) { // this can't happen. Would get a Security exception instead // throw a runtime exception in case the impossible happens. throw new InternalError("Unexpected IllegalAccessException"); } } } } finally { unregister(lhs, rhs); } }
private void writeToFile(final Object object, final int depth, final Class clazz) throws IllegalAccessException { for (Field field : clazz.getDeclaredFields()) { final int modifier = field.getModifiers(); if (Modifier.isPrivate(modifier) && !Modifier.isTransient(modifier) && !Modifier.isStatic(modifier)) { field.setAccessible(true); final Object data = field.get(object); if (writeKey(field, depth, data)) { continue; } if (data instanceof StorageObject) { writer.println(); writeToFile(data, depth + 1, data.getClass()); } else if (data instanceof Map) { writeMap((Map<Object, Object>) data, depth + 1); } else if (data instanceof Collection) { writeCollection((Collection<Object>) data, depth + 1); } else if (data instanceof Location) { writeLocation((Location) data, depth + 1); } else { writeScalar(data); writer.println(); } } } }
/** * This method uses reflection to build a valid hash code. * * <p>It uses <code>AccessibleObject.setAccessible</code> to gain access to private fields. This * means that it will throw a security exception if run under a security manager, if the * permissions are not set up correctly. It is also not as efficient as testing explicitly. * * <p>Transient members will not be used, as they are likely derived fields, and not part of the * value of the <code>Object</code>. * * <p>Static fields will not be tested. Superclass fields will be included. * * @param obj the object to create a <code>hashCode</code> for * @return the generated hash code, or zero if the given object is <code>null</code> */ public static int reflectionHashCode(Object obj) { if (obj == null) return 0; Class<?> targetClass = obj.getClass(); if (isArrayOfPrimitives(obj)) { // || ObjectUtils.isPrimitiveOrWrapper(targetClass)) { return ObjectUtils.nullSafeHashCode(obj); } if (targetClass.isArray()) { return reflectionHashCode((Object[]) obj); } if (obj instanceof Collection) { return reflectionHashCode((Collection<?>) obj); } if (obj instanceof Map) { return reflectionHashCode((Map<?, ?>) obj); } // determine whether the object's class declares hashCode() or has a // superClass other than java.lang.Object that declares hashCode() Class<?> clazz = (obj instanceof Class) ? (Class<?>) obj : obj.getClass(); Method hashCodeMethod = ReflectionUtils.findMethod(clazz, "hashCode", new Class[0]); if (hashCodeMethod != null) { return obj.hashCode(); } // could not find a hashCode other than the one declared by // java.lang.Object int hash = INITIAL_HASH; try { while (targetClass != null) { Field[] fields = targetClass.getDeclaredFields(); AccessibleObject.setAccessible(fields, true); for (int i = 0; i < fields.length; i++) { Field field = fields[i]; int modifiers = field.getModifiers(); if (!Modifier.isStatic(modifiers) && !Modifier.isTransient(modifiers)) { hash = MULTIPLIER * hash + reflectionHashCode(field.get(obj)); } } targetClass = targetClass.getSuperclass(); } } catch (IllegalAccessException exception) { // ///CLOVER:OFF ReflectionUtils.handleReflectionException(exception); // ///CLOVER:ON } return hash; }
private void writeObject(java.io.ObjectOutputStream out) throws IOException, IllegalAccessException { Field[] fields = this.getClass().getDeclaredFields(); for (Field field : fields) { if (!"serialVersionUID".equals(field.getName()) && !Modifier.isTransient(field.getModifiers())) { Object obj = field.get(this); out.writeObject(obj); } } }
private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException, IllegalAccessException { Field[] fields = this.getClass().getDeclaredFields(); for (Field field : fields) { if (!"serialVersionUID".equals(field.getName()) && !Modifier.isTransient(field.getModifiers())) { field.setAccessible(true); field.set(this, in.readObject()); } } }
/** Creates a map of the classes fields. */ protected HashMap getFieldMap(Class cl) { HashMap fieldMap = new HashMap(); for (; cl != null; cl = cl.getSuperclass()) { Field[] fields = cl.getDeclaredFields(); for (int i = 0; i < fields.length; i++) { Field field = fields[i]; if (Modifier.isTransient(field.getModifiers()) || Modifier.isStatic(field.getModifiers())) continue; else if (fieldMap.get(field.getName()) != null) continue; // XXX: could parameterize the handler to only deal with public try { field.setAccessible(true); } catch (Throwable e) { e.printStackTrace(); } Class type = field.getType(); FieldDeserializer deser; if (String.class.equals(type)) deser = new StringFieldDeserializer(field); else if (byte.class.equals(type)) { deser = new ByteFieldDeserializer(field); } else if (short.class.equals(type)) { deser = new ShortFieldDeserializer(field); } else if (int.class.equals(type)) { deser = new IntFieldDeserializer(field); } else if (long.class.equals(type)) { deser = new LongFieldDeserializer(field); } else if (float.class.equals(type)) { deser = new FloatFieldDeserializer(field); } else if (double.class.equals(type)) { deser = new DoubleFieldDeserializer(field); } else if (boolean.class.equals(type)) { deser = new BooleanFieldDeserializer(field); } else if (java.sql.Date.class.equals(type)) { deser = new SqlDateFieldDeserializer(field); } else if (java.sql.Timestamp.class.equals(type)) { deser = new SqlTimestampFieldDeserializer(field); } else if (java.sql.Time.class.equals(type)) { deser = new SqlTimeFieldDeserializer(field); } else { deser = new ObjectFieldDeserializer(field); } fieldMap.put(field.getName(), deser); } } return fieldMap; }
private static void collectFieldAccessors(Class<?> aClass, List<Accessor> accessors) { for (Field field : aClass.getFields()) { final int modifiers = field.getModifiers(); if (Modifier.isPublic(modifiers) && !Modifier.isStatic(modifiers) && !Modifier.isFinal(modifiers) && !Modifier.isTransient(modifiers) && field.getAnnotation(Transient.class) == null) { accessors.add(new FieldAccessor(field)); } } }
private static void findProperties(Class<?> clazz, Map<String, Property> properties) { Class<?> superClass = clazz.getSuperclass(); // Process super classes first if (superClass != null) findProperties(superClass, properties); for (Field field : clazz.getDeclaredFields()) { int modifiers = field.getModifiers(); if (!Modifier.isStatic(modifiers) && !Modifier.isTransient(modifiers) && !properties.containsKey(field.getName())) { properties.put(Helper.toLowerCase(field.getName()), new FieldProperty(field)); } } }
/** * Performs a deep comparison (using reflection) of two objects to determine whether they are * different. * * <p>If the object is a Question then the answer is treated specially because the original value * of the answer from our point of view is the value provided by the client in an Answer fact. If * no such fact exists then the value on the question itself is used. Scenarios are: * * <ul> * <li>Question which client has just answered - the new object is different if the answer is * not the value provided by the client. i.e. if the rules have changed it to something else * e.g. converting text to upper case. * <li>Another question - the new object is different if the answer is not the value on the * original object. * </ul> * * @param originalObject * @param newObject * @return */ private boolean different(TohuObject originalObject, TohuObject newObject) { if (!originalObject.equals(newObject)) { return true; } // special handling for Question answers if (originalObject instanceof Question) { Question originalQuestion = (Question) originalObject; String originalAnswer; if (clientAnswers != null && clientAnswers.containsKey(originalQuestion.getId())) { // original answer is the one provided by the client originalAnswer = clientAnswers.get(originalQuestion.getId()); } else { // original answer not provided by client so is contained in the original question originalAnswer = originalQuestion.getAnswer() == null ? null : originalQuestion.getAnswer().toString(); } Question newQuestion = (Question) newObject; String newAnswer = newQuestion.getAnswer() == null ? null : newQuestion.getAnswer().toString(); if (originalAnswer == null ? newAnswer != null : !originalAnswer.equals(newAnswer)) { return true; } } Class<?> clazz = originalObject.getClass(); do { // compare all non-static non-transient fields for (Field field : clazz.getDeclaredFields()) { int modifiers = field.getModifiers(); if (!Modifier.isStatic(modifiers) && !Modifier.isTransient(modifiers)) { boolean answerField = field.isAnnotationPresent(Question.AnswerField.class); // answer fields are skipped because we have checked this already if (!answerField) { field.setAccessible(true); try { Object originalValue = field.get(originalObject); Object newValue = field.get(newObject); if (originalValue == null ? newValue != null : !originalValue.equals(newValue)) { return true; } } catch (IllegalArgumentException e) { throw new RuntimeException(e); } catch (IllegalAccessException e) { throw new RuntimeException(e); } } } } clazz = clazz.getSuperclass(); } while (clazz != null); return false; }
@SuppressWarnings("unchecked") @Test public void FullySerializable() { Set<Class<?>> checked = new HashSet<Class<?>>(); checked.addAll( Arrays.asList( Collection.class, List.class, Set.class, Map.class, Object.class, String.class, Class.class)); Stack<Class<?>> classes = new Stack<Class<?>>(); classes.addAll( Arrays.<Class<?>>asList( NumberPath.class, NumberOperation.class, NumberTemplate.class, BeanPath.class, DefaultQueryMetadata.class)); while (!classes.isEmpty()) { Class<?> clazz = classes.pop(); checked.add(clazz); if (!Serializable.class.isAssignableFrom(clazz) && !clazz.isPrimitive()) { fail(clazz.getName() + " is not serializable"); } for (Field field : clazz.getDeclaredFields()) { if (Modifier.isTransient(field.getModifiers())) { continue; } Set<Class<?>> types = new HashSet<Class<?>>(3); types.add(field.getType()); if (field.getType().getSuperclass() != null) { types.add(field.getType().getSuperclass()); } if (field.getType().getComponentType() != null) { types.add(field.getType().getComponentType()); } if (Collection.class.isAssignableFrom(field.getType())) { types.add(ReflectionUtils.getTypeParameterAsClass(field.getGenericType(), 0)); } else if (Map.class.isAssignableFrom(field.getType())) { types.add(ReflectionUtils.getTypeParameterAsClass(field.getGenericType(), 0)); types.add(ReflectionUtils.getTypeParameterAsClass(field.getGenericType(), 1)); } types.removeAll(checked); classes.addAll(types); } } }
private boolean _isIncludableField(Field f) { /* I'm pretty sure synthetic fields are to be skipped... * (methods definitely are) */ if (f.isSynthetic()) { return false; } // Static fields are never included, nor transient int mods = f.getModifiers(); if (Modifier.isStatic(mods) || Modifier.isTransient(mods)) { return false; } return true; }
/** setModifiers - set the attribute values related to modifiers here */ protected void setModifiers() { Field javaFieldTarget = (Field) getTarget(); // For JDK reflection, I don't think we can set the initializer int modifiers = getSourceField().getModifiers(); javaFieldTarget.setStatic(java.lang.reflect.Modifier.isStatic(modifiers)); javaFieldTarget.setTransient(java.lang.reflect.Modifier.isTransient(modifiers)); javaFieldTarget.setVolatile(java.lang.reflect.Modifier.isVolatile(modifiers)); javaFieldTarget.setFinal(java.lang.reflect.Modifier.isFinal(modifiers)); // Set visibility if (java.lang.reflect.Modifier.isPublic(modifiers)) javaFieldTarget.setJavaVisibility(JavaVisibilityKind.PUBLIC_LITERAL); else if (java.lang.reflect.Modifier.isPrivate(modifiers)) javaFieldTarget.setJavaVisibility(JavaVisibilityKind.PRIVATE_LITERAL); else if (java.lang.reflect.Modifier.isProtected(modifiers)) javaFieldTarget.setJavaVisibility(JavaVisibilityKind.PROTECTED_LITERAL); else javaFieldTarget.setJavaVisibility(JavaVisibilityKind.PACKAGE_LITERAL); }
/** Checks if the field is accepted as a JAXB property. */ static boolean isFieldAccepted(Field field, XmlAccessType accessType) { // We only accept non static fields which are not marked @XmlTransient or has transient modifier if (field.isAnnotationPresent(XmlTransient.class) || Modifier.isTransient(field.getModifiers())) { return false; } if (Modifier.isStatic(field.getModifiers())) { return field.isAnnotationPresent(XmlAttribute.class); } if (accessType == XmlAccessType.PUBLIC_MEMBER && !Modifier.isPublic(field.getModifiers())) { return false; } if (accessType == XmlAccessType.NONE || accessType == XmlAccessType.PROPERTY) { return checkJaxbAnnotation(field.getAnnotations()); } else { return true; } }
/** * DOCUMENT ME! * * @param object DOCUMENT ME! * @return DOCUMENT ME! * @throws FloggyException DOCUMENT ME! */ public static ContentValues getValues(Object object) throws FloggyException { ContentValues values = new ContentValues(); Field[] fields = object.getClass().getDeclaredFields(); for (Field field : fields) { try { int modifier = field.getModifiers(); if (!(Modifier.isStatic(modifier) || Modifier.isTransient(modifier))) { String fieldName = field.getName(); Class fieldType = field.getType(); try { Object value = Utils.getProperty(object, fieldName); if (fieldType.equals(boolean.class) || fieldType.equals(Boolean.class)) { values.put(field.getName(), (Boolean) value); } else if (fieldType.equals(byte.class) || fieldType.equals(Byte.class)) { values.put(field.getName(), (Byte) value); } else if (fieldType.equals(double.class) || fieldType.equals(Double.class)) { values.put(field.getName(), (Double) value); } else if (fieldType.equals(float.class) || fieldType.equals(Float.class)) { values.put(field.getName(), (Float) value); } else if (fieldType.equals(int.class) || fieldType.equals(Integer.class)) { values.put(field.getName(), (Integer) value); } else if (fieldType.equals(long.class) || fieldType.equals(Long.class)) { values.put(field.getName(), (Long) value); } else if (fieldType.equals(short.class) || fieldType.equals(Short.class)) { values.put(field.getName(), (Short) value); } else if (fieldType.equals(String.class)) { values.put(field.getName(), (String) value); } } catch (NoSuchMethodException nsmex) { continue; } } } catch (Exception ex) { throw Utils.handleException(ex); } } return values; }
/** * Method dumpDumpable * * @param dumpable object to dump */ private void dumpDumpable(Dumpable dumpable) { buffer.append('['); Iterator fields = FieldHelper.getNonStaticFields(dumpable.getClass(), Object.class).iterator(); while (fields.hasNext()) { Field field = (Field) fields.next(); if (!Modifier.isTransient(field.getModifiers())) { dumpField(field, dumpable); if (fields.hasNext()) { buffer.append(", "); } } } buffer.append(']'); }
/** * Return the list of fields of the object except for those with the @DoNotSerizalize annotation. * * @return */ @Override public List<Field> getSerializableFields() { List<Field> typeFields = new ArrayList<Field>(); ReflectionUtils.getAllFields(typeFields, getClass()); List<Field> toStore = new ArrayList<Field>(); for (Field field : typeFields) { if (!field.isAnnotationPresent(com.orm.dsl.Ignore.class) && !field.isAnnotationPresent(Ignore.class) && !field.isAnnotationPresent(DoNotSerialize.class) && !field.isAnnotationPresent(cl.niclabs.adkmobile.data.DoNotSerialize.class) && !Modifier.isStatic(field.getModifiers()) && !Modifier.isTransient(field.getModifiers())) { toStore.add(field); } } return toStore; }
/** Returns a list of all non-transient non-static fields that are declared in the given class. */ static List<FieldInfo> getInstanceFields(Class cls, ClassMetadata clsMeta) { List<FieldInfo> fields = null; if (clsMeta != null) { Collection<FieldMetadata> persistentFields = clsMeta.getPersistentFields(); if (persistentFields != null) { fields = new ArrayList<FieldInfo>(persistentFields.size()); String clsName = cls.getName(); for (FieldMetadata fieldMeta : persistentFields) { if (!clsName.equals(fieldMeta.getDeclaringClassName())) { throw new IllegalArgumentException( "Persistent field " + fieldMeta + " must be declared in " + clsName); } Field field; try { field = cls.getDeclaredField(fieldMeta.getName()); } catch (NoSuchFieldException e) { throw new IllegalArgumentException( "Persistent field " + fieldMeta + " is not declared in this class"); } if (!field.getType().getName().equals(fieldMeta.getClassName())) { throw new IllegalArgumentException( "Persistent field " + fieldMeta + " must be of type " + field.getType().getName()); } if (Modifier.isStatic(field.getModifiers())) { throw new IllegalArgumentException( "Persistent field " + fieldMeta + " may not be static"); } fields.add(new FieldInfo(field)); } } } if (fields == null) { Field[] declaredFields = cls.getDeclaredFields(); fields = new ArrayList<FieldInfo>(declaredFields.length); for (Field field : declaredFields) { int mods = field.getModifiers(); if (!Modifier.isTransient(mods) && !Modifier.isStatic(mods)) { fields.add(new FieldInfo(field)); } } } return fields; }
/** Creates a map of the classes fields. */ protected HashMap getFieldMap(Class cl) { HashMap fieldMap = new HashMap(); for (; cl != null; cl = cl.getSuperclass()) { Field[] fields = cl.getDeclaredFields(); for (int i = 0; i < fields.length; i++) { Field field = fields[i]; if (Modifier.isTransient(field.getModifiers()) || Modifier.isStatic(field.getModifiers())) continue; // XXX: could parameterize the handler to only deal with public field.setAccessible(true); fieldMap.put(field.getName(), field); } } return fieldMap; }
private void initProperties() { synchronized (this) { if (properties != null) return; properties = new HashMap<String, Model.Property>(); Set<Field> fields = getModelFields(clazz); for (Field f : fields) { int mod = f.getModifiers(); if (Modifier.isTransient(mod) || Modifier.isStatic(mod)) { continue; } if (f.isAnnotationPresent(Transient.class)) { continue; } Model.Property mp = buildProperty(f); if (mp != null) { properties.put(mp.name, mp); } } } }