Java问题,如何从未知对象获取方法的值 [英] Java Question, how to get the value of a method from an unknown object

查看:62
本文介绍了Java问题,如何从未知对象获取方法的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在系统中定义了很多对象,也许有1000个对象, 其中一些具有这种方法:

I have lots of object defined in the system, perhaps 1000 objects, and some of them have this method:

public Date getDate();

无论如何,我可以执行以下操作:

Is there anyway I can do something like this:

Object o = getFromSomeWhere.....;

Method m = o.getMethod("getDate");
Date date = (Date) m.getValue();

推荐答案

如果可以使它们全部实现接口,那肯定是最好的选择.但是,反射也将起作用,并且您的代码几乎在那里:

If you can make them all implement an interface, that would certainly be the best option. However, reflection will also work, and your code was nearly there:

Object o = getFromSomeWhere.....;
Method m = o.getClass().getMethod("getDate");
Date date = (Date) m.invoke(o);

(坦白地说,您需要处理很多异常)

(There's a bunch of exceptions you'll need to handle, admittedly...)

举一个完整的例子:

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

public class Test
{
    public static void main(String[] args) throws Exception
    {
        Object o = new Test();
        Method m = o.getClass().getMethod("getDate");
        Date date = (Date) m.invoke(o);
        System.out.println(date);
    }

    public Date getDate()
    {
        return new Date();
    }
}

这篇关于Java问题,如何从未知对象获取方法的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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