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

31
LINES

< > BotCompany Repo | #1005599 // nuEmptyObject - fast way to make an empty instance of a class (using default constructor)

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

Libraryless. Click here for Pure Java version (7528L/42K).

static Map<Class, Constructor> nuEmptyObject_cache = newDangerousWeakHashMap();

static <A> A nuEmptyObject(Class<A> c) ctex {
  Constructor ctr;
  
  synchronized(nuEmptyObject_cache) {
    ctr = nuEmptyObject_cache.get(c);
    if (ctr == null) {
      nuEmptyObject_cache.put(c, ctr = nuEmptyObject_findConstructor(c));
      makeAccessible(ctr);
    }
  }

  try {
    ret (A) ctr.newInstance();
  } catch (InstantiationException e) {
    if (empty(e.getMessage()))
      if ((c.getModifiers() & Modifier.ABSTRACT) != 0)
        fail("Can't instantiate abstract class " + className(c), e);
      else
        fail("Can't instantiate " + className(c), e);  
    else throw rethrow(e);
  }
}

static Constructor nuEmptyObject_findConstructor(Class c) {
  for (Constructor m : getDeclaredConstructors_cached(c))
    if (m.getParameterTypes().length == 0)
      ret m;
  fail("No default constructor declared in " + c.getName());
}

Author comment

Began life as a copy of #1001136

download  show line numbers  debug dex  old transpilations   

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

No comments. add comment

Snippet ID: #1005599
Snippet name: nuEmptyObject - fast way to make an empty instance of a class (using default constructor)
Eternal ID of this version: #1005599/10
Text MD5: 5856fab1a26b8fc0e34ac3ca926c8425
Transpilation MD5: 01b54238145bb60fe4839aa8030664e8
Author: stefan
Category: javax
Type: JavaX fragment (include)
Public (visible to everyone): Yes
Archived (hidden from active list): No
Created/modified: 2022-03-29 19:42:53
Source code size: 962 bytes / 31 lines
Pitched / IR pitched: No / No
Views / Downloads: 577 / 690
Version history: 9 change(s)
Referenced in: [show references]