Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package org.devtcg.testwebservices;
- import java.lang.reflect.Field;
- /**
- * On Dalvik, reflection methods cannot be trusted to perform lookups with
- * reasonable efficiency. All of the methods return deep copies of the
- * underlying cached structures and methods that lookup by name perform a linear
- * search for a match. So, we need our own custom class cache here to ensure
- * maximum performance reading our data binding classes.
- */
- public class ClassCache<T> {
- private final Class<T> mClazz;
- private HashMap<String, AnnotationCache<Field>> mFieldsByName;
- private AnnotationCache<Field>[] mFieldsWithAnnotations;
- private Field[] mFields;
- public ClassCache(Class<T> clazz) {
- mClazz = clazz;
- }
- public AnnotationCache<Field> getFieldWithAnnotations(String name) throws NoSuchFieldException {
- if (mFieldsByName == null) {
- mFieldsByName = getFieldsByName();
- }
- AnnotationCache<Field> field = mFieldsByName.get(name);
- if (field == null) {
- throw new NoSuchFieldException(name);
- } else {
- return field;
- }
- }
- public Field getField(String name) throws NoSuchFieldException {
- return getFieldWithAnnotations(name).getElement();
- }
- public AnnotationCache<Field>[] getFieldsWithAnnotations() {
- if (mFieldsWithAnnotations == null) {
- Field[] fields = getFields();
- int N = fields.length;
- AnnotationCache<Field>[] fieldsWithAnnotations = new AnnotationCache[N];
- for (int i = 0; i < N; i++) {
- fieldsWithAnnotations[i] = new AnnotationCache<Field>(fields[i]);
- }
- mFieldsWithAnnotations = fieldsWithAnnotations;
- }
- return mFieldsWithAnnotations;
- }
- public Field[] getFields() {
- if (mFields == null) {
- mFields = mClazz.getFields();
- }
- return mFields;
- }
- private HashMap<String, AnnotationCache<Field>> getFieldsByName() {
- HashMap<String, AnnotationCache<Field>> map =
- new HashMap<String, AnnotationCache<Field>>();
- Field[] array = getFields();
- int N = array.length;
- for (int i = 0; i < N; i++) {
- Field field = array[i];
- map.put(field.getName(), new AnnotationCache<Field>(field));
- }
- return map;
- }
- }
Add Comment
Please, Sign In to add comment