Solved

Regarding Java Reflection API

Posted on 2004-08-31
21
386 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 75 total points
ID: 11940368
0
 
LVL 18

Expert Comment

by:armoghan
ID: 11940370
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
Technology Partners: 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 20 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 40 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 20 total points
ID: 11940451
Method[] method = class.getDeclaredMethods();

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

Assisted Solution

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

Assisted Solution

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

Assisted Solution

by:armoghan
armoghan earned 75 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 75 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

Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

Suggested Solutions

Java functions are among the best things for programmers to work with as Java sites can be very easy to read and prepare. Java especially simplifies many processes in the coding industry as it helps integrate many forms of technology and different d…
Basic understanding on "OO- Object Orientation" is needed for designing a logical solution to solve a problem. Basic OOAD is a prerequisite for a coder to ensure that they follow the basic design of OO. This would help developers to understand the b…
This tutorial covers a practical example of lazy loading technique and early loading technique in a Singleton Design Pattern.
Viewers will learn how to properly install Eclipse with the necessary JDK, and will take a look at an introductory Java program. Download Eclipse installation zip file: Extract files from zip file: Download and install JDK 8: Open Eclipse and …

749 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