Java问题,如何从未知对象中获取方法的值

我在系统中定义了很多对象,可能有1000个对象,其中一些有这个方法:

public Date getDate(); 

无论如何,我可以做这样的事情:

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

如果你可以让它们都实现一个接口,那肯定是最好的选择。 但是,reflection也会起作用,你的代码几乎就在那里:

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

(无可否认,你需要处理一些例外……)

完整的例子:

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

尝试这个:

 Object aDate = new Date(); Method aMethod = aDate.getClass().getMethod("getDate", (Class[]) null); Object aResult = aMethod.invoke(aDate, (Void) null); 

您应该添加try-catch以确定在调用之前是否确实存在getDate方法。

如果有一个需要getDate()方法的接口,您可以使用以下代码进行检查:

 if (o instance of GetDateInterface){ GetDateInterface foo = (GetDateInterface) o; Date d = foo.getDate(); } 

为了完成其他答案,我还要确定带有接口的类。 我就是这样做的

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

如果你不介意额外的依赖,BeanUtils可以为你做这件事。