File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Java in General and the fly likes Java Reflection Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "Java Reflection" Watch "Java Reflection" New topic
Author

Java Reflection

Shantanu Nilawar
Greenhorn

Joined: Jul 13, 2006
Posts: 2
Hi,
I have test class having method setInt(int i){} into it. I have another class called testClass. I am using reflection into it. The test class is as follows:
class testClass
{
public static void main(String[] args)
{
Class cl = Class.forName("test");
}
}

Now I have to call the method setInt(int i) from the class test.java here. I know I have to use newInstance method of the class Class and then cast it to the test and then call the method. But my question is by just passing the class name string can I create the Object of that class?

I dont want to do the following:

test obj = (test) cl.newInstance();
obj.setInt(5);

Please advice
Shantanu
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 13875
    
  10

Use the getMethod(...) method on the Class object to find the java.lang.reflect.Method object that represents the setInt method. Use the invoke(...) method on the Method object to invoke the setInt method on the instance of your class test.

See the API documentation and The Java Tutorial: Trail: The Reflection API


Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 7 API documentation
Scala Notes - My blog about Scala
Shantanu Nilawar
Greenhorn

Joined: Jul 13, 2006
Posts: 2
Thanks for replying,but again the same problem, for calling invove method on Method class I need a Object of the class test which I dont have at this time.

Shantanu
Stan James
(instanceof Sidekick)
Ranch Hand

Joined: Jan 29, 2003
Posts: 8791
Sounds like you see how to get the Method object from the class, and now need to call Method.invoke().

If you're going to call a non-static method you'll need an instance of "test". No way around that. Class.forName().newInstance() is the reflection way to get one.

If you're going to call a static method, you can do it with null for the "object" parameter.

Is that what you need to know?
[ July 13, 2006: Message edited by: Stan James ]

A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Java Reflection
 
Similar Threads
Confusing code from JQ++
Visibility of private variables
TreeMap containsKey issue
Evaluating Strings
Calling a method from the command prompt