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


< > BotCompany Repo | #1001101 // "getOpt" function (get field by reflection, return null if not there)

JavaX fragment (include)

static O getOpt(O o, S field) {
  ret getOpt_cached(o, field);

static O mapMethodLike getOpt(S field, O o) {
  ret getOpt_cached(o, field);

static Object getOpt_raw(Object o, String field) ctex {
  Field f = getOpt_findField(o.getClass(), field);
  if (f == null) null;
  ret f.get(o);

// access of static fields is not yet optimized
static O getOpt(Class c, String field) ctex {
  if (c == null) null;
  Field f = getOpt_findStaticField(c, field);
  if (f == null) null;
  ret f.get(null);

static Field getOpt_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)
        return f;
    _c = _c.getSuperclass();
  } while (_c != null);
  ret null;

Author comment

Began life as a copy of #1000597

download  show line numbers  debug dex  old transpilations   

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

Comments [hide]

ID Author/Program Comment Date
1208 stefan getOpt can be passed a null 1st argument - then it just returns null. Useful for cascaded optionality, e.g.:

static S printableUserName() {
// Custom or Slack name, depending on what's available
ret or((S) callOpt(getBot("#1002355"), "getUserName"), getUserName());
2016-01-27 01:28:45

add comment

Snippet ID: #1001101
Snippet name: "getOpt" function (get field by reflection, return null if not there)
Eternal ID of this version: #1001101/9
Text MD5: 91e56345ffd108ce4905ab8367478f85
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:55:44
Source code size: 894 bytes / 34 lines
Pitched / IR pitched: No / No
Views / Downloads: 1352 / 7295
Version history: 8 change(s)
Referenced in: [show references]