Calling a method using reflection

我怕爱的太早我们不能终老 提交于 2020-01-02 05:23:26

问题


Is it possible to call a method by reflection from a class?

class MyObject {
    ...   //some methods

    public void fce() {
        //call another method of this object via reflection?
    }
}

Thank you.


回答1:


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


public class Main
{
    public static void main(final String[] argv)
    {
        final Main main;

        main = new Main();
        main.foo();
    }

    public void foo()
    {
        final Class clazz;
        final Method method;

        clazz = Main.class;

        try
        {
            method = clazz.getDeclaredMethod("bar", String.class);
            method.invoke(this, "foo");
        }
        catch(final NoSuchMethodException ex)
        {
            // handle it however you want
            ex.printStackTrace();
        }
        catch(final IllegalAccessException ex)
        {
            // handle it however you want
            ex.printStackTrace();
        }
        catch(final InvocationTargetException ex)
        {
            // handle it however you want
            ex.printStackTrace();
        }
    }

    private void bar(final String msg)
    {
        System.out.println("hello from: " + msg);
    }
}



回答2:


Absolutely:

import java.lang.reflect.*;

public class Test
{
    public static void main(String args[]) throws Exception
    {
        Test test = new Test();
        Method method = Test.class.getMethod("sayHello");
        method.invoke(test);
    }

    public void sayHello()
    {
        System.out.println("Hello!");
    }
}

If you have problems, post a specific question (preferrably with a short but complete program demonstrating the problem) and we'll try to sort it out.




回答3:


You can.. But there's are probably better ways to do what you're after (?). To call a method via reflection you could do something like -

class Test {

    public void foo() {
        // do something...
    }

    public void bar() {
        Method method = getClass.getMethod("foo");
        method.invoke(this);
    }
}

If the method you want to invoke has arguments then it's slightly different - you need to pass arguments to the invoke method in addition to the object to invoke it on, and when you get the method from the Class you need to specify a list of argument types. i.e. String.class etc.



来源:https://stackoverflow.com/questions/566418/calling-a-method-using-reflection

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!