Regarding Java Reflection API

sudhakar_koundinya
sudhakar_koundinya used Ask the Experts™
on
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
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Mick BarryJava Developer
Top Expert 2010

Commented:
> 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.

Starting with Angular 5

Learn the essential features and functions of the popular JavaScript framework for building mobile, desktop and web applications.

Commented:
have a look at reflection api. good place to start.
run time you need to exact names.
Mick BarryJava Developer
Top Expert 2010

Commented:
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);
Top Expert 2016

Commented:
>>String str=(String)(class.getMethods()[0]).substring(0,10);

What would you be attempting to do there?

Author

Commented:
I am just looking at this

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

How does this help me

Commented:
typo,
run time you need not to know names or methods.
Top Expert 2016

Commented:
You invoke the Method, not a String

Author

Commented:
>>What would you be attempting to do there?

That is just Pseudo . I am trying to execute runtime methods
Mick BarryJava Developer
Top Expert 2010

Commented:
> 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.

Top Expert 2016
Commented:
>>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
Mick BarryJava Developer
Top Expert 2010
Commented:
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);

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

method[index].invoke(class,method[index].getParameterTypes());
Mick BarryJava Developer
Top Expert 2010
Commented:
Distinguished Expert 2018
Commented:
Commented:
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
Commented:
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

Author

Commented:
thanks all of you guys

I understand what I need to do now :-)
Distinguished Expert 2018

Commented:
:)
Top Expert 2016

Commented:
8-)

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial