使用反射调用方法 [英] Calling a method using reflection

查看:136
本文介绍了使用反射调用方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以通过类的反射来调用方法?

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?
    }
}

谢谢。

推荐答案

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

这篇关于使用反射调用方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆