Extracting objects from a *collection* using reflection

  • Thread starter Sébastien de Mapias
  • Start date
S

Sébastien de Mapias

Hi,

Once I've retrieved the methods of a class using reflection,
I find the following for example:
~ method.getName(): "getTickets"
~ method.getGenericReturnType():
"java.util.List<com.my.project.stuff.Ticket>"
~ method.getReturnType(): "interface java.util.List"

Now I'd like to access the list of Tickets I have and run against
each
of them the 'getDeclaredMethods()' to invoke their methods, one after
each other.
But when passing "method.invoke(myObj, (Object[])null)", i.e. when
invoking 'getTickets(), and passing the returned object to my
procedure
that does the job, then when I execute again the following
~ Class<?> klass = Class.forName(myObj.getClass().getName());
~ Method[] methods = klass.getDeclaredMethods();
and loop through the methods, I get those of java.util.List of course
('trimToSize', 'ensureCapacity'...).

My procedure is recursive (I want to traverse a series of objects in
cascade,
get at their methods, retrieve references...).

This is not what I want: I want to access every method of Ticket
(getFare(),
getReduction() etc.) *inside* of my java.util.List.

Is there a way to nicely do this ? (I mean rather than tokenizing my
array
of [com.my...Ticket@67546754, com.my...Ticket@87638493, ...] and
looping
through these string references)

Thanks a lot !
Best regards,
Sébastien
 
S

softwarepearls_com

Are all your Tickets instances of the same class? If so, then IMO you
are confusing things. If they're all from the same class, then they
have the same API, so you would not want to waste time with
getDeclaredMethods() for every Ticket in your List.

Also, if this is just playing with Reflection to learn the API, fine..
but if this is for a real application, I would advise against falling
prey to reflection's attractions. Reflection often gets abused to
solve some problem which can normally be solved using proper OO
design. In my experience 4 out of 5 uses of reflection in commercial
systems have been pure obfuscation (reflection could have been avoided
completely).
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,770
Messages
2,569,584
Members
45,075
Latest member
MakersCBDBloodSupport

Latest Threads

Top