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

44
LINES

< > BotCompany Repo | #1000891 // "setOpt" function (set field by reflection, don't complain if not there)

JavaX fragment (include)

static void setOpt(Object o, String field, Object value) {
  if (o == null) ret;
  if (o instanceof Class) setOpt((Class) o, field, value);
  else try {
    Field f = setOpt_findField(o.getClass(), field);
    if (f != null)
      smartSet(f, o, value);
  } catch (Exception e) {
    throw new RuntimeException(e);
  }
}

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() & Modifier.STATIC) != 0)
        return f;
    _c = _c.getSuperclass();
  } while (_c != null);
  ret null;
}

static Field setOpt_findField(Class<?> c, String field) {
  Class _c = c;
  do {
    for (Field f : _c.getDeclaredFields())
      if (f.getName().equals(field))
        return f;
    _c = _c.getSuperclass();
  } while (_c != null);
  ret null;
}

Author comment

Began life as a copy of #1000415

download  show line numbers  debug dex  old transpilations   

Travelled to 15 computer(s): aoiabmzegqzx, bhatertpkbcr, cbybwowwnfue, cfunsshuasjs, ddnzoavkxhuk, gwrvuhgaqvyk, ishqpsrjomds, lpdgvwnxivlt, mqqgnosmbjvj, onxytkatvevr, pyentgdyhuwx, pzhvpgtvlbxg, tslmcundralx, tvejysmllsmz, vouqrxazstgt

No comments. add comment

Snippet ID: #1000891
Snippet name: "setOpt" function (set field by reflection, don't complain if not there)
Eternal ID of this version: #1000891/1
Text MD5: c1ee0bd846571ad20dd9063d668f71c5
Author: stefan
Category: javax
Type: JavaX fragment (include)
Public (visible to everyone): Yes
Archived (hidden from active list): No
Created/modified: 2016-11-19 16:32:40
Source code size: 1165 bytes / 44 lines
Pitched / IR pitched: No / No
Views / Downloads: 681 / 6008
Referenced in: #1001148 - x27.java (JavaX)
#1001370 - x28.java (JavaX)
#1001600 - x29.java (JavaX)
#1002427 - Accellerating 629 (SPIKE)
#1002772 - hasField - does a class or an object have a certain field?
#1004305 - x31.java (JavaX)
#1005598 - setOpt, setOpt_findField, optimized for objects (but not for classes yet, LIVE)
#1009441 - setOpt_raw function (set field by reflection, ignore if it's a Map)
#3000382 - Answer for ferdie (>> t = 1, f = 0)