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

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 : c.getDeclaredConstructors())
    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   

Travelled to 10 computer(s): aoiabmzegqzx, cbybwowwnfue, cfunsshuasjs, ddnzoavkxhuk, gwrvuhgaqvyk, ishqpsrjomds, lpdgvwnxivlt, mqqgnosmbjvj, tslmcundralx, tvejysmllsmz

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: 338 / 302
Version history: 8 change(s)
Referenced in: [show references]