public Object newInstance ( Class c ) throws InstantiationException , IllegalAccessException { Object ret = null ; Method [ ] methods = c . getDeclaredMethods ( ) ; Method m ; int modifiers ; // searching for static methods: for ( int i = 0 ; i < methods . length ; i ++ ) { m = methods [ i ] ; modifiers = m . getModifiers ( ) ; if ( ( modifiers & Modifier . STATIC ) != 0 ) { // searching for public access: if ( ( modifiers & Modifier . PUBLIC ) != 0 ) { // searching for no parameters: if ( m . getParameterTypes ( ) . length == 0 ) { // searching for return type: if ( m . getReturnType ( ) == c ) { // searching for substring "instance" in method name: if ( m . getName ( ) . toLowerCase ( ) . indexOf ( "instance" ) != - 1 ) { try { // Finally we found a singleton method: // we are static and don't need an instance. ret = m . invoke ( null , dummyParameters ) ; } catch ( IllegalArgumentException e ) { // This will not happen: // we ensured that no arguments are needed. e . printStackTrace ( ) ; } catch ( IllegalAccessException e ) { // This will not happen (only in applet context perhaps or with some // SecurityManager): // we ensured public access. e . printStackTrace ( ) ; } catch ( InvocationTargetException e ) { e . printStackTrace ( ) ; } } } } } } } // check, if we found a singleton: if ( ret == null ) { // try to invoke the default constructor: Constructor [ ] constructors = c . getConstructors ( ) ; Constructor con = null ; // search for a parameterless constructor: for ( int i = 0 ; i < constructors . length ; i ++ ) { con = constructors [ i ] ; if ( con . getParameterTypes ( ) . length == 0 ) { // see, if public: modifiers = con . getModifiers ( ) ; try { if ( ( modifiers & Modifier . PUBLIC ) == 0 ) { // try to set accessible: con . setAccessible ( true ) ; } // invokes the default constructor ret = c . newInstance ( ) ; } catch ( SecurityException se ) { // damn } } } } if ( ret == null ) { System . err . println ( "Unable to instantiate: " + c . getName ( ) + ": no singleton method, no public default constructor." ) ; } return ret ; }
Dynamic instantiation of the given type with singleton retrieval support as described in this class description .