Invoke method of an object - reflect

8

Is it possible to invoke a method from a content of a String variable?

for (Object vlr : dados) {
    String metodo = "getCodigo()";
    contato.setAttribute("codigo", vlr.metodo);
}
    
asked by anonymous 24.09.2015 / 20:15

2 answers

12
package java.lang.reflect;
...
//Obtenha a classe pela instancia 
Class clazz = Class.forName( seuObjeto.getClass().getName()  );

//Obtenha o metodo da classe pelo nome
Method metodoDoSeuObjeto = clazz.getMethod( "nomeMetodo" );

//invoque o metodo no seu objeto. "se necessario passe um array de argumentos."
Object retornoDoMetodo = metodoDoSeuObjeto.invoke( seuObjeto, ArrayArgumentos );
    
24.09.2015 / 20:36
4

Here is a simple example of how you would play with reflection: link

And the reflection documentation link link

UPDATE 2

Here is the code for the simple example:

import java.util.*;
import java.lang.*;
import java.lang.reflect.Method;

class Test
{  
    public static void main(String[] args) throws Exception {
        String className = "TestReflection";
        String[] methodsNames = {"method1", "method2"};

        Class<?> clazz = Class.forName(className);
        Object instanceOfClass =  clazz.newInstance();

        for(String s : methodsNames) {
            Class<?>[] paramTypes = null;
            Method m = clazz.getDeclaredMethod(s, paramTypes);
            Object[] varargs = null;
            m.invoke(instanceOfClass, varargs);

            System.out.println(m);
        }
    }
}

class TestReflection {

    public void method1() {
        System.out.println("Method1 chamado");
    }

    public void method2() {
        System.out.println("Method2 chamado");
    }
}
    
24.09.2015 / 21:08