Not logged in.  Login/Logout/Register | List snippets | | Create snippet | Upload image Upload data

70
LINES

< > BotCompany Repo | #1005598 - setOpt, setOpt_findField, optimized (LIVE)

JavaX fragment (include) [tags: use-pretranspiled]

Libraryless. Click here for Pure Java version (2199L/14K).

please include function getOpt_cached.

// Some people use this.
static Field setOpt_findField(Class c, S field) {
  HashMap<S, Field> map;
  synchronized(getOpt_cache) {
    map = getOpt_cache.get(c);
    if (map == null)
      map = getOpt_makeCache(c);
  }
  ret map.get(field);
}

static void setOpt(Object o, String field, Object value) ctex {
  if (o == null) ret;
  
  ifclass _SetField
    if (o instanceof _SetField) ret with o/_SetField._setField(field, value);
  endif
  
  Class c = o.getClass();
  HashMap<S, Field> map;
  
  if (getOpt_cache == null)
    map = getOpt_makeCache(c); // in class init
  else synchronized(getOpt_cache) {
    map = getOpt_cache.get(c);
    if (map == null)
      map = getOpt_makeCache(c);
  }
  
  if (map == getOpt_special) {
    if (o instanceof Class) {
      setOpt((Class) o, field, value);
      ret;
    }
    
    // It's probably a subclass of Map. Use raw method
    setOpt_raw(o, field, value);
    ret;
  }
  
  Field f = map.get(field);
  if (f != null)
    smartSet(f, o, value); // possible improvement: skip setAccessible
}

static void setOpt(Class c, String field, Object value) {
  if (c == null) ret;
  try {
    Field f = setOpt_findStaticField(c, field);
    if (f != null)
      smartSet(f, null, value);
  } catch (Exception e) {
    throw new RuntimeException(e);
  }
}
  
static Field setOpt_findStaticField(Class<?> c, String field) {
  Class _c = c;
  do {
    for (Field f : _c.getDeclaredFields())
      if (f.getName().equals(field) && (f.getModifiers() & java.lang.reflect.Modifier.STATIC) != 0) {
        makeAccessible(f);
        return f;
      }
    _c = _c.getSuperclass();
  } while (_c != null);
  ret null;
}

Author comment

Began life as a copy of #1000891

download  show line numbers  debug dex   

Travelled to 14 computer(s): aoiabmzegqzx, cbybwowwnfue, cfunsshuasjs, gwrvuhgaqvyk, irmadwmeruwu, ishqpsrjomds, jozkyjcghlvl, lpdgvwnxivlt, mqqgnosmbjvj, onxytkatvevr, podlckwnjdmb, tslmcundralx, tvejysmllsmz, whxojlpjdney

No comments. add comment

Snippet ID: #1005598
Snippet name: setOpt, setOpt_findField, optimized (LIVE)
Eternal ID of this version: #1005598/9
Text MD5: d2fb4695b38854abea36f90da6bece4d
Transpilation MD5: ed771cbe396dccc2aaff809efebdceee
Author: stefan
Category: javax
Type: JavaX fragment (include)
Public (visible to everyone): Yes
Archived (hidden from active list): No
Created/modified: 2019-08-31 14:56:31
Source code size: 1763 bytes / 70 lines
Pitched / IR pitched: No / No
Views / Downloads: 402 / 703
Version history: 8 change(s)
Referenced in: [show references]