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 (2097L/14K).

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 : c.getDeclaredConstructors())
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/9
Text MD5: bda093e042bc7a87aafcfd0d628d3f08
Transpilation MD5: ad132e2a9c387a0a7a3738c8478696fd
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:50:25
Source code size: 956 bytes / 31 lines
Pitched / IR pitched: No / No
Views / Downloads: 466 / 477
Version history: 8 change(s)
Referenced in: [show references]