Regarding Java Reflection API

Hello All,

I am newbie to java reflection API. could u please give me some valuable pointers to understand them??

for example

class Test
{
           public static void main(String s[])
           {
                            test(new String("Hi there"));
           }
          static void test(Object o)
          {
                       //at this pointer I don't know what are the data and method members of that object
                       // I can go for instanceof but the problem is at runtime if i have multiple classes then it would be problem for
                      // writing such codes as it deals with multiple if and else conditions

                     //If I go with object.getClass() that will be faster for me. But my problem is
                      // how to work with data and method members of object
                       //I know I have method called class.getMethods() in Class
                       //But when it comes to runtime I am not understaindg How to execute that runtime methods.
                          // in otherwords I wanted to have following type of example for an example
                             // String str=(String)(class.getMethods()[0]).substring(0,10);
                             
          }
}

I hope you understand my query

thanks
Sudhakar
LVL 14
sudhakar_koundinyaAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

armoghanCommented:
0
objectsCommented:
> I can go for instanceof but the problem is at runtime if i have multiple classes then it would be > problem for writing such codes as it deals with multiple if and else conditions

Reflection is not really going to help you there ( or perhaps you need to explain the big picture).

Sounds like you'd be better off having your objects implement an interface that defines the methods you need to call so you don't need to worry about if/else.

0
Cloud Class® Course: C++ 11 Fundamentals

This course will introduce you to C++ 11 and teach you about syntax fundamentals.

expertmbCommented:
have a look at reflection api. good place to start.
run time you need to exact names.
0
objectsCommented:
you could use the getMethods() to get all the methods for the class but then you'll still need to loop thru them all to see if what you are after is availble.
to call it you'd then use:

Method m = ...
Object result = m.invoke(o, args);
0
CEHJCommented:
>>String str=(String)(class.getMethods()[0]).substring(0,10);

What would you be attempting to do there?
0
sudhakar_koundinyaAuthor Commented:
I am just looking at this

String result = (String) theMethods[0].invoke
(requestParam, null);

How does this help me
0
expertmbCommented:
typo,
run time you need not to know names or methods.
0
CEHJCommented:
You invoke the Method, not a String
0
sudhakar_koundinyaAuthor Commented:
>>What would you be attempting to do there?

That is just Pseudo . I am trying to execute runtime methods
0
objectsCommented:
> String result = (String) theMethods[0].invoke(requestParam, null);
> How does this help me

allows you to call method (at runtime).
from what you've said so far, I'm not sure if it does help you.

I guess if you wanted to call specific method on an object if it exists (regardless of class) then thats the way to go.

0
CEHJCommented:
>>That is just Pseudo . I am trying to execute runtime methods

OK. The code i posted you the other day for timing method calls does just this. Simply look at the code
0
objectsCommented:
eg. to look for a method name myfunction that takes no parameters you could use:

Class c = o.getClass();
Method[] methods = c.getMethods();
for (int i=0; i<methods.length; i++)
{
   if (methods[i].getName().equals("myfunction") && 
       methods[i].getParamaterTypes().length==0)
   {
      result = methods[i].invoke(o, null);
   }
}

Thopugh in this case it would be simply to get the appropriate method directly from the class, depends on your requirements.

eg. Method m = c.getMethod("myfunction", null);

0
expertmbCommented:
Method[] method = class.getDeclaredMethods();

method[index].invoke(class,method[index].getParameterTypes());
0
objectsCommented:
0
armoghanCommented:
Why and when use reflection?
There are four basic uses of reflection:
1. Performing type discovery – Allows you to examine the types in an assembly and interact with or instantiate those types.
2. Late binding to methods and properties – Allows the programmer to invoke properties and methods on objects dynamically instantiated based on type discovery.  This is also known as dynamic invocation.
3. Viewing metadata (attributes) – Especially useful for examining custom attributes and building tools to support those attributes.
4. Creating types at runtime (Reflection Emit) – Allows you to create entirely new types at runtime and then use those types in your code.

http://www.cs.arizona.edu/classes/cs386/fall02/handouts/30.html
0
armoghanCommented:
When Not to Use Reflection

You should not use reflection when simpler or more natural options are available. For example, you should use an interface with derived class implementations (polymorphism) to switch between method implementations rather than querying the type of an object to determine what code should be executed in an if statement. Also, you should not use reflection to deal with type information at runtime when it would be simpler to let the compiler deal with the type information at compile time. Capricious use of reflection usually makes your code harder to debug and maintain. As an analogy, you should not use a space shuttle to drive to the supermarket!

and

http://www.javalobby.org/thread.jspa?messageID=3936&threadID=1188&forumID=46
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
sudhakar_koundinyaAuthor Commented:
thanks all of you guys

I understand what I need to do now :-)
0
girionisCommented:
:)
0
CEHJCommented:
8-)
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Java

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.