问题
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();
回答1:
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...)
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();
}
}
回答2:
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.
回答3:
If there is an interface requiring a getDate() method you can check using the following code:
if (o instance of GetDateInterface){
GetDateInterface foo = (GetDateInterface) o;
Date d = foo.getDate();
}
回答4:
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);
}
}
回答5:
If you don't mind the extra dependency, BeanUtils can do this for you.
来源:https://stackoverflow.com/questions/796312/java-question-how-to-get-the-value-of-a-method-from-an-unknown-object