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

70
LINES

< > BotCompany Repo | #1022197 // Call default method by reflection Spike [OK]

JavaX source code (desktop) [tags: use-pretranspiled] - run with: x30.jar

Download Jar. Libraryless. Click here for Pure Java version (6067L/43K).

!7

sinterface Bla {
  default S bla() { ret "ok"; }
}

sclass Blubb implements Bla {
}

sclass Overridden implements Bla {
  public S bla() { ret "different!"; }
}

sclass OverriddenSubclass extends Overridden {}

p-exp {
  assertEqualsVerbose("ok", call(new Blubb, "bla"));
  assertEqualsVerbose("different!", call(new Overridden, "bla"));
  print("===");
  assertEqualsVerbose("different!", call(new OverriddenSubclass, "bla"));
}

final sclass _MethodCache {
  final Class c;
  final HashMap<S, L<Method>> cache = new HashMap;
  
  *(Class *c) { _init(); }
  
  void _init() {
    Class _c = c;
    while (_c != null) {
      for (Method m : _c.getDeclaredMethods()) {
        m.setAccessible(true);
        if (m.getName().equals("bla")) print("Found: " + m);
        multiMapPut(cache, m.getName(), m);
      }
      
      _c = _c.getSuperclass();
    }
    
    // add default methods
    for (Class intf : allInterfacesImplementedBy(c))
      for (Method m : intf.getDeclaredMethods())
        if (m.isDefault()) {
          m.setAccessible(true);
          if (m.getName().equals("bla")) print("Found: " + m);
          multiMapPut(cache, m.getName(), m);
        }
          
    ifdef _MethodCache_debug
      print("MethodCache " + this + ": " + className(c) + " => " + keys(cache));
    endifdef
  }

  // Returns only matching methods
  Method findMethod(S method, O[] args) ctex {
    L<Method> m = cache.get(method);
    ifdef _MethodCache_debug
      print("findMethod " + this + ": " + className(c) + "/" + method + " => " + m);
    endifdef
    if (m == null) null;
    int n = m.size();
    for i to n: {
      Method me = m.get(i);
      if (call_checkArgs(me, args, false))
        ret me;
    }
    null;
  }
}

download  show line numbers  debug dex  old transpilations   

Travelled to 7 computer(s): bhatertpkbcr, cfunsshuasjs, mqqgnosmbjvj, pyentgdyhuwx, pzhvpgtvlbxg, tvejysmllsmz, vouqrxazstgt

No comments. add comment

Snippet ID: #1022197
Snippet name: Call default method by reflection Spike [OK]
Eternal ID of this version: #1022197/12
Text MD5: 4893e26e8793e21cf5ce691bc92fc619
Transpilation MD5: d172293d8747b7496e55063d4d434767
Author: stefan
Category: javax
Type: JavaX source code (desktop)
Public (visible to everyone): Yes
Archived (hidden from active list): No
Created/modified: 2019-03-11 10:22:32
Source code size: 1803 bytes / 70 lines
Pitched / IR pitched: No / No
Views / Downloads: 247 / 726
Version history: 11 change(s)
Referenced in: [show references]