public static Object constructByNamedParams ( Class clazz , Map params ) throws Exception { Object obj = clazz . getConstructor ( ) . newInstance ( ) ; Method [ ] allMethods = clazz . getMethods ( ) ; for ( Method method : allMethods ) { if ( method . getName ( ) . startsWith ( "set" ) ) { Object [ ] o = new Object [ 1 ] ; String propertyName = Introspector . decapitalize ( method . getName ( ) . substring ( 3 ) ) ; if ( params . containsKey ( propertyName ) ) { o [ 0 ] = params . get ( propertyName ) ; method . invoke ( obj , o ) ; } } } return obj ; }
Build an object out of a given class and a map for field names to values .