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

45
LINES

< > BotCompany Repo | #1000415 - "set" function (set field by reflection)

JavaX fragment (include)

static <A> A set(A o, String field, Object value) {
  if (o == null) null;
  if (o instanceof Class) set((Class) o, field, value);
  else try {
    Field f = set_findField(o.getClass(), field);
    makeAccessible(f);
    smartSet(f, o, value);
  } catch (Exception e) {
    throw new RuntimeException(e);
  }
  ret o;
}

static void set(Class c, String field, Object value) {
  if (c == null) ret;
  try {
    Field f = set_findStaticField(c, field);
    makeAccessible(f);
    smartSet(f, null, value);
  } catch (Exception e) {
    throw new RuntimeException(e);
  }
}
  
static Field set_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);
  throw new RuntimeException("Static field '" + field + "' not found in " + c.getName());
}

static Field set_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);
  throw new RuntimeException("Field '" + field + "' not found in " + c.getName());
}

download  show line numbers  debug dex   

Travelled to 10 computer(s): aoiabmzegqzx, cbybwowwnfue, cfunsshuasjs, gwrvuhgaqvyk, ishqpsrjomds, lpdgvwnxivlt, mqqgnosmbjvj, onxytkatvevr, tslmcundralx, tvejysmllsmz

Comments [hide]

ID Author/Program Comment Date
974 #1000604 (pitcher) 2015-08-20 15:28:24

add comment

Snippet ID: #1000415
Snippet name: "set" function (set field by reflection)
Eternal ID of this version: #1000415/9
Text MD5: 66d6f16d0a2eb32e02333277da059967
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:50:09
Source code size: 1322 bytes / 45 lines
Pitched / IR pitched: No / No
Views / Downloads: 591 / 7496
Version history: 8 change(s)
Referenced in: [show references]