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

41
LINES

< > BotCompany Repo | #1001136 - nuObject - calls constructor with arguments

JavaX fragment (include)

1  
static O nuObject(S className, O... args) ctex {
2  
  ret nuObject(classForName(className), args);
3  
}
4  
5  
// too ambiguous - maybe need to fix some callers
6  
/*static O nuObject(O realm, S className, O... args) {
7  
  ret nuObject(_getClass(realm, className), args);
8  
}*/
9  
10  
static <A> A nuObject(Class<A> c, O... args) ctex {
11  
  if (args.length == 0) ret nuObjectWithoutArguments(c); // cached!
12  
  
13  
  Constructor m = nuObject_findConstructor(c, args);
14  
  makeAccessible(m);
15  
  return (A) m.newInstance(args);
16  
}
17  
18  
static Constructor nuObject_findConstructor(Class c, Object... args) {
19  
  for (Constructor m : c.getDeclaredConstructors()) {
20  
    if (!nuObject_checkArgs(m.getParameterTypes(), args, false))
21  
      continue;
22  
    return m;
23  
  }
24  
  fail("Constructor " + c.getName() + getClasses(args) + " not found"
25  
    + (args.length == 0 && (c.getModifiers() & java.lang.reflect.Modifier.STATIC) == 0 ? " - hint: it's a non-static class!" : ""));
26  
}
27  
28  
 static boolean nuObject_checkArgs(Class[] types, Object[] args, boolean debug) {
29  
    if (types.length != args.length) {
30  
      if (debug)
31  
        System.out.println("Bad parameter length: " + args.length + " vs " + types.length);
32  
      return false;
33  
    }
34  
    for (int i = 0; i < types.length; i++)
35  
      if (!(args[i] == null || isInstanceX(types[i], args[i]))) {
36  
        if (debug)
37  
          System.out.println("Bad parameter " + i + ": " + args[i] + " vs " + types[i]);
38  
        return false;
39  
      }
40  
    return true;
41  
  }

download  show line numbers  debug dex   

Travelled to 14 computer(s): aoiabmzegqzx, bhatertpkbcr, cbybwowwnfue, cfunsshuasjs, gwrvuhgaqvyk, ishqpsrjomds, lpdgvwnxivlt, mqqgnosmbjvj, onxytkatvevr, pyentgdyhuwx, pzhvpgtvlbxg, tslmcundralx, tvejysmllsmz, wtqryiryparv

No comments. add comment

Snippet ID: #1001136
Snippet name: nuObject - calls constructor with arguments
Eternal ID of this version: #1001136/9
Text MD5: cb5c4e23fc43429c026eb927d7438b09
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:57:13
Source code size: 1487 bytes / 41 lines
Pitched / IR pitched: No / No
Views / Downloads: 565 / 4152
Version history: 8 change(s)
Referenced in: [show references]

Formerly at http://tinybrain.de/1001136 & http://1001136.tinybrain.de