File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
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

Java Reflection

Shantanu Nilawar

Joined: Jul 13, 2006
Posts: 2
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 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();

Please advice
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 15080

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 8 API documentation
Shantanu Nilawar

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.

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
I agree. Here's the link:
subject: Java Reflection
It's not a secret anymore!