Java 问题,如何从未知对象获取方法的值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/796312/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java Question, how to get the value of a method from an unknown object
提问by jojo
I have lots of object defined in the system, perhaps 1000 objects, and some of them have this method:
我在系统中定义了很多对象,大概有 1000 个对象,其中一些有这个方法:
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();
回答by Jon Skeet
If you canmake 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...)
(诚然,您需要处理许多例外情况......)
For a full example:
完整示例:
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();
}
}
回答by Azder
Try this:
试试这个:
Object aDate = new Date();
Method aMethod = aDate.getClass().getMethod("getDate", (Class<Void>[]) null);
Object aResult = aMethod.invoke(aDate, (Void) null);
You should add try-catch to determine if there really is a method getDate before invoking.
您应该在调用之前添加 try-catch 以确定是否确实存在 getDate 方法。
回答by jjnguy
If there is an interface requiring a getDate() method you can check using the following code:
如果有需要 getDate() 方法的接口,您可以使用以下代码进行检查:
if (o instance of GetDateInterface){
GetDateInterface foo = (GetDateInterface) o;
Date d = foo.getDate();
}
回答by Henrik Paul
To complete the other answer(s), I'd also identify the classes with an interface. This is how I'd do it
为了完成其他答案,我还将用接口标识类。这就是我要做的
import java.util.Date;
interface Dated {
public Date getDate();
public void setDate(Date date);
}
class FooObject implements Dated {
private Date date;
public void setDate(Date date) { this.date = date; }
public Date getDate() { return date; }
// other code...
}
public static void main (String[] args) {
Object o = getRandomObject(); // implemented elsewhere
if (o instanceof Dated) {
Date date = ((Dated)o).getDate();
doStuffWith(date);
}
}
回答by sproketboy
If you don't mind the extra dependency, BeanUtils can do this for you.
如果你不介意额外的依赖,BeanUtils 可以为你做这件事。

