This week's book giveaway is in the Other Languages forum.
We're giving away four copies of Functional Reactive Programming and have Stephen Blackheath and Anthony Jones on-line!
See this thread for details.
Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Java Reflection

 
Shantanu Nilawar
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 15490
43
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Shantanu Nilawar
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic