Question

I have a string as such:

String[] names = new String[] {"FirstMethod", "SecondMethod"...} //200 of these

At the moment I have to type in manually:

public void onSuccess( Map<String,ControlService.RegisterValues> result ) {

    for( String Name : result.keySet() ){

        message+=result.get(Name).FirstMethod+", ";
        message+=result.get(Name).SecondMethod+", ";
        //I call the method here - I'd like to use the list above to call it in though

Obviously I don't want to be typing out 200 times, is there a way I can use this list, convert it into a method name, and loop over that?

EDIT:

Class I'm calling it from:

public interface ControlService extends RemoteJsonService
{

public void I2CRegisterValues( String [] Names, AsyncCallback<Map<String,RegisterValues>> callback); 

public class RegisterValues
{
    int FirstMethod;
    //etc.
Was it helpful?

Solution

You can access a method using Class.getMethod, which returns a Method object. You then invoke that Method object by passing it the instance and arguments:

method.invoke(result.get(Name), whateverArguments);

Your question was a bit ambiguous as to whether you're really accessing a field. If that's the case, you can get a Field via Class.getField, and get its value via the get method, again passing in the instance on which you want to get the field.

In either case, the result is typed as Object, and you need to downcast that to the expected type. In the case of a primitive like int, the object returned will be a boxed type like Integer, which you can auto-unbox to int:

int foo = (Integer) method.invoke(...);

The whole thing would look something like:

Field field = I2CRegisterValues.getField(fieldName);
Object o = field.get(result.get(Name));
int fieldValue = (Integer) o;

... where fieldName is a String variable in a loop of your String[] names. You can also do the above as a one-liner:

int fieldValue = (Integer) I2CRegisterValues
    .getField(fieldName)
    .get(result.get(Name));

OTHER TIPS

Class.getMethod(methodName).invoke(....);

See the API for more info: http://docs.oracle.com/javase/7/docs/api/java/lang/Class.html

     //load desired Class at runtime
  Class classObj = Class.forName("xyz.abc.YourClassName");
  Object obj = classObj .newInstance();

 //invoke specific method at runtime
     for( String methodName : result.keySet() ){
       Method method = cls.getDeclaredMethod(methodName , noparams);
       method.invoke(obj, null);
      }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top