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

26
LINES

< > BotCompany Repo | #2000492 // call function(s) for reflective calls (e.g. to hotwired objects)

New Tinybrain snippet

  static Object call(Class c, String method, Object... args) ctex {
    Method m = call_findStaticMethod(c, method, args);
    m.setAccessible(true);
    return m.invoke(null, args);
  }
  
  static Object call(Object o, String method, Object... args) ctex {
    Method m = call_findMethod(o, method, args);
    m.setAccessible(true);
    return m.invoke(o, args);
  }
  
  static Method call_findMethod(Object o, String method, Object[] args) {
    // TODO: go to superclasses too
    for (Method m : o.getClass().getDeclaredMethods())
      if (m.getName().equals(method) && (m.getModifiers() & Modifier.STATIC) == 0 && m.getParameterTypes().length == args.length) // TODO: multicast
        return m;
    throw new RuntimeException("Method '" + method + "' with " + args.length + " parameter(s) not found in " + o.getClass().getName());
  }
  
  static Method call_findStaticMethod(Class<?> c, String method, Object[] args) {
    for (Method m : c.getDeclaredMethods())
      if (m.getName().equals(method) && (m.getModifiers() & Modifier.STATIC) != 0 && m.getParameterTypes().length == args.length) // TODO: multicast
        return m;
    throw new RuntimeException("Static method '" + method + "' with " + args.length + " parameter(s) not found in " + c.getName());
  }

download  show line numbers   

Snippet is not live.

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

No comments. add comment

Snippet ID: #2000492
Snippet name: call function(s) for reflective calls (e.g. to hotwired objects)
Eternal ID of this version: #2000492/1
Text MD5: 54565f37057521dd8e889d1c4b88eecf
Author: stefan
Category:
Type: New Tinybrain snippet
Public (visible to everyone): Yes
Archived (hidden from active list): No
Created/modified: 2015-08-03 01:10:00
Source code size: 1300 bytes / 26 lines
Pitched / IR pitched: No / Yes
Views / Downloads: 635 / 183
Referenced in: [show references]