Guest User

Untitled

a guest
Feb 21st, 2018
69
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.39 KB | None | 0 0
  1. package org.devtcg.testwebservices;
  2.  
  3. import java.lang.reflect.Field;
  4.  
  5. /**
  6.  * On Dalvik, reflection methods cannot be trusted to perform lookups with
  7.  * reasonable efficiency. All of the methods return deep copies of the
  8.  * underlying cached structures and methods that lookup by name perform a linear
  9.  * search for a match. So, we need our own custom class cache here to ensure
  10.  * maximum performance reading our data binding classes.
  11.  */
  12. public class ClassCache<T> {
  13.     private final Class<T> mClazz;
  14.  
  15.     private HashMap<String, AnnotationCache<Field>> mFieldsByName;
  16.     private AnnotationCache<Field>[] mFieldsWithAnnotations;
  17.     private Field[] mFields;
  18.  
  19.     public ClassCache(Class<T> clazz) {
  20.         mClazz = clazz;
  21.     }
  22.  
  23.     public AnnotationCache<Field> getFieldWithAnnotations(String name) throws NoSuchFieldException {
  24.         if (mFieldsByName == null) {
  25.             mFieldsByName = getFieldsByName();
  26.         }
  27.         AnnotationCache<Field> field = mFieldsByName.get(name);
  28.         if (field == null) {
  29.             throw new NoSuchFieldException(name);
  30.         } else {
  31.             return field;
  32.         }
  33.     }
  34.  
  35.     public Field getField(String name) throws NoSuchFieldException {
  36.         return getFieldWithAnnotations(name).getElement();
  37.     }
  38.  
  39.     public AnnotationCache<Field>[] getFieldsWithAnnotations() {
  40.         if (mFieldsWithAnnotations == null) {
  41.             Field[] fields = getFields();
  42.             int N = fields.length;
  43.             AnnotationCache<Field>[] fieldsWithAnnotations = new AnnotationCache[N];
  44.             for (int i = 0; i < N; i++) {
  45.                 fieldsWithAnnotations[i] = new AnnotationCache<Field>(fields[i]);
  46.             }
  47.             mFieldsWithAnnotations = fieldsWithAnnotations;
  48.         }
  49.         return mFieldsWithAnnotations;
  50.     }
  51.  
  52.     public Field[] getFields() {
  53.         if (mFields == null) {
  54.             mFields = mClazz.getFields();
  55.         }
  56.         return mFields;
  57.     }
  58.  
  59.     private HashMap<String, AnnotationCache<Field>> getFieldsByName() {
  60.         HashMap<String, AnnotationCache<Field>> map =
  61.                 new HashMap<String, AnnotationCache<Field>>();
  62.         Field[] array = getFields();
  63.         int N = array.length;
  64.         for (int i = 0; i < N; i++) {
  65.             Field field = array[i];
  66.             map.put(field.getName(), new AnnotationCache<Field>(field));
  67.         }
  68.         return map;
  69.     }
  70. }
Add Comment
Please, Sign In to add comment