Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

Regarding Java Reflection API

Posted on 2004-08-31
21
Medium Priority
?
390 Views
Last Modified: 2008-03-04
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
0
Comment
Question by:sudhakar_koundinya
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 5
  • 4
  • 4
  • +3
21 Comments
 
LVL 18

Assisted Solution

by:armoghan
armoghan earned 300 total points
ID: 11940368
0
 
LVL 92

Expert Comment

by:objects
ID: 11940386
> 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
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 6

Expert Comment

by:expertmb
ID: 11940395
have a look at reflection api. good place to start.
run time you need to exact names.
0
 
LVL 92

Expert Comment

by:objects
ID: 11940397
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
 
LVL 86

Expert Comment

by:CEHJ
ID: 11940399
>>String str=(String)(class.getMethods()[0]).substring(0,10);

What would you be attempting to do there?
0
 
LVL 14

Author Comment

by:sudhakar_koundinya
ID: 11940400
I am just looking at this

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

How does this help me
0
 
LVL 6

Expert Comment

by:expertmb
ID: 11940405
typo,
run time you need not to know names or methods.
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 11940411
You invoke the Method, not a String
0
 
LVL 14

Author Comment

by:sudhakar_koundinya
ID: 11940412
>>What would you be attempting to do there?

That is just Pseudo . I am trying to execute runtime methods
0
 
LVL 92

Expert Comment

by:objects
ID: 11940415
> 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
 
LVL 86

Assisted Solution

by:CEHJ
CEHJ earned 80 total points
ID: 11940431
>>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
 
LVL 92

Assisted Solution

by:objects
objects earned 160 total points
ID: 11940438
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
 
LVL 6

Assisted Solution

by:expertmb
expertmb earned 80 total points
ID: 11940451
Method[] method = class.getDeclaredMethods();

method[index].invoke(class,method[index].getParameterTypes());
0
 
LVL 92

Assisted Solution

by:objects
objects earned 160 total points
ID: 11940463
0
 
LVL 35

Assisted Solution

by:girionis
girionis earned 80 total points
ID: 11940507
0
 
LVL 18

Assisted Solution

by:armoghan
armoghan earned 300 total points
ID: 11940799
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
 
LVL 18

Accepted Solution

by:
armoghan earned 300 total points
ID: 11940810
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
 
LVL 14

Author Comment

by:sudhakar_koundinya
ID: 11940866
thanks all of you guys

I understand what I need to do now :-)
0
 
LVL 35

Expert Comment

by:girionis
ID: 11940906
:)
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 11944636
8-)
0

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

An old method to applying the Singleton pattern in your Java code is to check if a static instance, defined in the same class that needs to be instantiated once and only once, is null and then create a new instance; otherwise, the pre-existing insta…
After being asked a question last year, I went into one of my moods where I did some research and code just for the fun and learning of it all.  Subsequently, from this journey, I put together this article on "Range Searching Using Visual Basic.NET …
Viewers learn how to read error messages and identify possible mistakes that could cause hours of frustration. Coding is as much about debugging your code as it is about writing it. Define Error Message: Line Numbers: Type of Error: Break Down…
This tutorial explains how to use the VisualVM tool for the Java platform application. This video goes into detail on the Threads, Sampler, and Profiler tabs.
Suggested Courses

715 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question