Solved

Regarding Java Reflection API

Posted on 2004-08-31
21
379 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
  • 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
 
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
What Is Threat Intelligence?

Threat intelligence is often discussed, but rarely understood. Starting with a precise definition, along with clear business goals, is essential.

 
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

What Is Threat Intelligence?

Threat intelligence is often discussed, but rarely understood. Starting with a precise definition, along with clear business goals, is essential.

Join & Write a Comment

Introduction Java can be integrated with native programs using an interface called JNI(Java Native Interface). Native programs are programs which can directly run on the processor. JNI is simply a naming and calling convention so that the JVM (Java…
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…
Viewers learn about the scanner class in this video and are introduced to receiving user input for their programs. Additionally, objects, conditional statements, and loops are used to help reinforce the concepts. Introduce Scanner class: Importing…
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…

757 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

Need Help in Real-Time?

Connect with top rated Experts

19 Experts available now in Live!

Get 1:1 Help Now