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

49
LINES

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

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

Libraryless. Click here for Pure Java version (2815L/16K).

1  
static <A> A set(A o, String field, Object value) {
2  
  if (o == null) null;
3  
  if (o instanceof Class) set((Class) o, field, value);
4  
  else try {
5  
    Field f = set_findField(o.getClass(), field);
6  
    makeAccessible(f);
7  
    smartSet(f, o, value);
8  
  } catch (Exception e) {
9  
    throw new RuntimeException(e);
10  
  }
11  
  ret o;
12  
}
13  
14  
static void set(Class c, String field, Object value) {
15  
  if (c == null) ret;
16  
  try {
17  
    Field f = set_findStaticField(c, field);
18  
    makeAccessible(f);
19  
    smartSet(f, null, value);
20  
  } catch (Exception e) {
21  
    throw new RuntimeException(e);
22  
  }
23  
}
24  
  
25  
static Field set_findStaticField(Class<?> c, String field) {
26  
  Class _c = c;
27  
  do {
28  
    for (Field f : _c.getDeclaredFields())
29  
      if (f.getName().equals(field) && (f.getModifiers() & java.lang.reflect.Modifier.STATIC) != 0)
30  
        return f;
31  
    _c = _c.getSuperclass();
32  
  } while (_c != null);
33  
  throw new RuntimeException("Static field '" + field + "' not found in " + c.getName());
34  
}
35  
36  
static Field set_findField(Class<?> c, String field) {
37  
  Class _c = c;
38  
  do {
39  
    for (Field f : _c.getDeclaredFields())
40  
      if (f.getName().equals(field))
41  
        return f;
42  
    _c = _c.getSuperclass();
43  
  } while (_c != null);
44  
  throw new RuntimeException("Field '" + field + "' not found in " + c.getName());
45  
}
46  
47  
svoid set(BitSet bs, int idx) {
48  
  bs?.set(idx);
49  
}

download  show line numbers  debug dex  old transpilations   

Travelled to 19 computer(s): aoiabmzegqzx, bhatertpkbcr, cbybwowwnfue, cfunsshuasjs, ekrmjmnbrukm, gwrvuhgaqvyk, ishqpsrjomds, lpdgvwnxivlt, mowyntqkapby, mqqgnosmbjvj, ofpaelxlmzfo, onxytkatvevr, podlckwnjdmb, pyentgdyhuwx, pzhvpgtvlbxg, tslmcundralx, tvejysmllsmz, vouqrxazstgt, xrpafgyirdlv

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/10
Text MD5: db6e606acc0f4e5d007860a82af356c6
Transpilation MD5: 43c76b3f93a7c8b2411bf635397e0058
Author: stefan
Category: javax
Type: JavaX fragment (include)
Public (visible to everyone): Yes
Archived (hidden from active list): No
Created/modified: 2021-06-04 21:35:39
Source code size: 1377 bytes / 49 lines
Pitched / IR pitched: No / No
Views / Downloads: 809 / 10000
Version history: 9 change(s)
Referenced in: [show references]