public static < T > T newInstance ( final Class < T > cls ) { if ( Modifier . isAbstract ( cls . getModifiers ( ) ) ) { if ( cls . equals ( Map . class ) ) { return ( T ) new HashMap <> ( ) ; } else if ( cls . equals ( List . class ) ) { return ( T ) new ArrayList <> ( ) ; } else if ( cls . equals ( Set . class ) ) { return ( T ) new HashSet <> ( ) ; } else if ( cls . equals ( Queue . class ) ) { return ( T ) new LinkedList <> ( ) ; } else if ( cls . equals ( Deque . class ) ) { return ( T ) new LinkedList <> ( ) ; } else if ( cls . equals ( SortedSet . class ) || cls . equals ( NavigableSet . class ) ) { return ( T ) new TreeSet <> ( ) ; } else if ( cls . equals ( SortedMap . class ) || cls . equals ( NavigableMap . class ) ) { return ( T ) new TreeMap <> ( ) ; } } try { if ( Modifier . isStatic ( cls . getModifiers ( ) ) == false && ( cls . isAnonymousClass ( ) || cls . isMemberClass ( ) ) ) { // http://stackoverflow.com/questions/2097982/is-it-possible-to-create-an-instance-of-nested-class-using-java-reflection final List < Class < ? > > toInstantiate = new ArrayList <> ( ) ; Class < ? > parent = cls . getEnclosingClass ( ) ; do { toInstantiate . add ( parent ) ; parent = parent . getEnclosingClass ( ) ; } while ( parent != null && Modifier . isStatic ( parent . getModifiers ( ) ) == false && ( parent . isAnonymousClass ( ) || parent . isMemberClass ( ) ) ) ; if ( parent != null ) { toInstantiate . add ( parent ) ; } N . reverse ( toInstantiate ) ; Object instance = null ; for ( Class < ? > current : toInstantiate ) { instance = instance == null ? invoke ( ClassUtil . getDeclaredConstructor ( current ) ) : invoke ( ClassUtil . getDeclaredConstructor ( current , instance . getClass ( ) ) , instance ) ; } return invoke ( ClassUtil . getDeclaredConstructor ( cls , instance . getClass ( ) ) , instance ) ; } else { return invoke ( ClassUtil . getDeclaredConstructor ( cls ) ) ; } } catch ( InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e ) { throw N . toRuntimeException ( e ) ; } }
Method newInstance .