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).

1  
static Map<Class, Constructor> nuEmptyObject_cache = newDangerousWeakHashMap();
2  
3  
static <A> A nuEmptyObject(Class<A> c) ctex {
4  
  Constructor ctr;
5  
  
6  
  synchronized(nuEmptyObject_cache) {
7  
    ctr = nuEmptyObject_cache.get(c);
8  
    if (ctr == null) {
9  
      nuEmptyObject_cache.put(c, ctr = nuEmptyObject_findConstructor(c));
10  
      makeAccessible(ctr);
11  
    }
12  
  }
13  
14  
  try {
15  
    ret (A) ctr.newInstance();
16  
  } catch (InstantiationException e) {
17  
    if (empty(e.getMessage()))
18  
      if ((c.getModifiers() & Modifier.ABSTRACT) != 0)
19  
        fail("Can't instantiate abstract class " + className(c), e);
20  
      else
21  
        fail("Can't instantiate " + className(c), e);  
22  
    else throw rethrow(e);
23  
  }
24  
}
25  
26  
static Constructor nuEmptyObject_findConstructor(Class c) {
27  
  for (Constructor m : getDeclaredConstructors_cached(c))
28  
    if (m.getParameterTypes().length == 0)
29  
      ret m;
30  
  fail("No default constructor declared in " + c.getName());
31  
}

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: 572 / 685
Version history: 9 change(s)
Referenced in: [show references]