Invoking an object’s method - reflect

Asked

Viewed 1,714 times

8

It is possible to invoke a method from the contents of a variable of type String?

for (Object vlr : dados) {
    String metodo = "getCodigo()";
    contato.setAttribute("codigo", vlr.metodo);
}
  • You want to create a method?!! Wouldn’t be invoking a method from the name (Reflection)?

  • Exactly, this, invoking, I will correct the question, could give me information about this Enforcement, of how I would use it to address my problem?

  • 1

    Very useful your question to me, did not know about Reflections, it was worth +1

  • 2

    Yes it is possible.

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 );

4

Here’s a simple example of how you would play with Regeneration: http://rextester.com/ODXCPL39550

And the link of the documentation on reflextion https://docs.oracle.com/javase/tutorial/reflect/member/methodInvocation.html


UPDATE 2

Follow the simple example code:

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");
    }
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.