public
Created

Java jquery.extend

  • Download Gist
gistfile1.java
Java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80
/**
* 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 );
}
}
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.