Skip to content

Instantly share code, notes, and snippets.

@jschappet
Created October 21, 2014 18:20
Show Gist options
  • Save jschappet/43aed3f5fd75bc270028 to your computer and use it in GitHub Desktop.
Save jschappet/43aed3f5fd75bc270028 to your computer and use it in GitHub Desktop.
@RequestMapping( value = "update/{hostId}", method = RequestMethod.POST )
@ResponseBody
public String updateValues(@PathVariable("hostId") String hostId,
@RequestParam("name") String attrName,
@RequestParam("value") String attrValue ) {
Host host = ictssysadminDaoService.getHostService().findById( Integer.parseInt(hostId ));
if (attrName.equals("description")) {
host.setDescription(attrValue);
}
ictssysadminDaoService.getHostService().save(host);
return "";
}
@rrlorentzen
Copy link

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class Refl {

private static final Log log = LogFactory.getLog( Refl.class );

static class Person {

    private String first;

    public String getFirst() {
        return first;
    }

    public void setFirst( String first ) {
        this.first = first;
    }

}

public static void main( String... args ) {

    Person person = new Person();

    String value = "ryan";
    String fieldName = "first";
    String methodName = "set" + StringUtils.capitalize( fieldName );

    log.debug( "methodName :: " + methodName );

    if ( Refl.methodExists( methodName, person.getClass(), new Class[] { String.class } ) ) {
        log.debug( "method exists" );
        try {

            Method method = person.getClass().getMethod( methodName, new Class[] { String.class } );
            method.invoke( person, new Object[] { value } );

        } catch ( NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e ) {
            log.error( "error calling " + methodName, e );
        }
    } else {
        log.debug( "method does not exist" );
    }

    log.debug( person.getFirst() );

}

@SuppressWarnings( value = { "all" } )
static boolean methodExists( String methodName, Class<? extends Object> clazz, Class[] params ) {
    try {
        clazz.getMethod( methodName, params ).getName();
    } catch ( Exception e ) {
        log.error( e.getMessage() );
        return false;
    }
    return true;
}

}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment