dynamic - Java Question, how to get the value of a method from an unknown object -


I have a lot of objects defined in the system, maybe 1000 objects, and some of them have this method:

  public date getDate ();  

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 an interface To implement, this would definitely be the best choice, however, reflection would also work, and your code was almost there:

  object o = getFromSomeWhere .....; Method m = o.getClass (). GetMethod ("getDate"); Date Date = (Date) m.invoke (o);  

(You must handle a bunch of exceptions ...)

For a complete example:

  Import java .lang.reflect *; Import java.util. *; Public class test {public static zero core (string [] args throws an exception {object o = new test (); Method m = o.getClass (). GetMethod ("getDate"); Date Date = (Date) m.invoke (o); Println (date); } Public date getDate () {new date (date); }}  

Comments

Popular posts from this blog

python - Overriding the save method in Django ModelForm -

html - CSS autoheight, but fit content to height of div -

qt - How to prevent QAudioInput from automatically boosting the master volume to 100%? -