Created
January 12, 2012 17:51
-
-
Save tbruyelle/1602045 to your computer and use it in GitHub Desktop.
Java jquery.extend
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Equivalent to jquery.extend : copy non null properties from origin to dest if exist | |
* | |
* @param orig | |
* @param dest | |
*/ | |
public static void extend( Object orig, Object dest ) | |
{ | |
if ( orig == null || dest == null ) | |
{ | |
throw new IllegalArgumentException( "extend: args are null" ); | |
} | |
for ( Method method : orig.getClass().getDeclaredMethods() ) | |
{ | |
String setterMethod; | |
if ( method.getName().startsWith( "get" ) ) | |
{ | |
setterMethod = method.getName().replaceFirst( "get", "set" ); | |
} | |
else if ( method.getName().startsWith( "is" ) ) | |
{ | |
setterMethod = method.getName().replaceFirst( "is", "set" ); | |
} | |
else | |
{ | |
logger.debug( "skip not a getter method {}", method.getName() ); | |
continue; | |
} | |
try | |
{ | |
Object value = method.invoke( orig ); | |
if ( value == null ) | |
{ | |
logger.debug( "skip null value for method {}", method.getName() ); | |
continue; | |
} | |
Method destMethod; | |
try | |
{ | |
destMethod = dest.getClass().getDeclaredMethod( method.getName() ); | |
} | |
catch ( NoSuchMethodException e1 ) | |
{ | |
try | |
{ | |
// handle possible clash between boolean primitive and object | |
// IDEs generate getter starting with get for Boolean field | |
destMethod = dest.getClass().getDeclaredMethod( method.getName().replaceFirst( "get", "is" ) ); | |
} | |
catch ( NoSuchMethodException e2 ) | |
{ | |
logger.debug( "skip non existing method {} in dest class", method.getName() ); | |
continue; | |
} | |
} | |
if ( !destMethod.getReturnType().isAssignableFrom( method.getReturnType() ) ) | |
{ | |
if ( destMethod.getReturnType().isPrimitive() && destMethod.getReturnType().equals( Boolean.TYPE ) | |
&& method.getReturnType().equals( Boolean.class ) ) | |
{ | |
// handle extend Boolean to boolean | |
} | |
else | |
{ | |
logger.debug( "skip non assignable method {} in dest class", method.getName() ); | |
continue; | |
} | |
} | |
dest.getClass().getDeclaredMethod( setterMethod, destMethod.getReturnType() ).invoke( dest, value ); | |
} | |
catch ( Exception e ) | |
{ | |
logger.error( "exeption while extending field {} from {}", method.getName(), | |
orig.getClass().getSimpleName() ); | |
logger.error( "dest class {}", dest.getClass().getSimpleName() ); | |
logger.error( "stacktrace: ", e ); | |
throw new RuntimeException( e ); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment