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)

static O nuObject(S className, O... args) ctex {
  ret nuObject(classForName(className), args);
}

// too ambiguous - maybe need to fix some callers
/*static O nuObject(O realm, S className, O... args) {
  ret nuObject(_getClass(realm, className), args);
}*/

static <A> A nuObject(Class<A> c, O... args) ctex {
  if (args.length == 0) ret nuObjectWithoutArguments(c); // cached!
  
  Constructor m = nuObject_findConstructor(c, args);
  makeAccessible(m);
  return (A) m.newInstance(args);
}

static Constructor nuObject_findConstructor(Class c, Object... args) {
  for (Constructor m : c.getDeclaredConstructors()) {
    if (!nuObject_checkArgs(m.getParameterTypes(), args, false))
      continue;
    return m;
  }
  fail("Constructor " + c.getName() + getClasses(args) + " not found"
    + (args.length == 0 && (c.getModifiers() & java.lang.reflect.Modifier.STATIC) == 0 ? " - hint: it's a non-static class!" : ""));
}

 static boolean nuObject_checkArgs(Class[] types, Object[] args, boolean debug) {
    if (types.length != args.length) {
      if (debug)
        System.out.println("Bad parameter length: " + args.length + " vs " + types.length);
      return false;
    }
    for (int i = 0; i < types.length; i++)
      if (!(args[i] == null || isInstanceX(types[i], args[i]))) {
        if (debug)
          System.out.println("Bad parameter " + i + ": " + args[i] + " vs " + types[i]);
        return false;
      }
    return true;
  }

download  show line numbers  debug dex   

Travelled to 13 computer(s): aoiabmzegqzx, bhatertpkbcr, cbybwowwnfue, cfunsshuasjs, gwrvuhgaqvyk, ishqpsrjomds, lpdgvwnxivlt, mqqgnosmbjvj, onxytkatvevr, 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: 531 / 4101
Version history: 8 change(s)
Referenced in: [show references]

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