aspose file tools*
The moose likes Java in General and the fly likes Calling class methods by class object using 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 "Calling class methods by class object using Reflection" Watch "Calling class methods by class object using Reflection" New topic
Author

Calling class methods by class object using Reflection

vikash talanki
Greenhorn

Joined: Oct 04, 2011
Posts: 4
hi all,

I am creating & compiling(using ant script) java classes at runtime in my java program. In the same program I wanna get the objects for these classes and set their varibales/methods with some values.

Suppose I have a class like

From my main java program I can easily set or call the method of myclass like

The above code is trivial if we already know everything about "myclass". But if I want to get the instance of myclass at runtime & call methods of the class , I am totally confused & struck at this point, I can say

Please help
Vijay Tidake
Ranch Hand

Joined: Nov 04, 2008
Posts: 146

Hi,

Look for the concept of type casting.
For your eg. you can call getVar() as follows.




Thanks


The important thing is not to stop questioning.Curiosity has its own reason for existing.
Jigar Gohil
Greenhorn

Joined: Dec 04, 2008
Posts: 11
I suggest you read the concept of Reflection in detail... there are methods available for fetching the methods & variables...
vikash talanki
Greenhorn

Joined: Oct 04, 2011
Posts: 4
@vijay Tidke

The probelm here is to get methods of class & then invoke them using object. According to your solution we need to know that there is method called getVar present in the class, what if we dont have idea of what methods are present in the class?
Vijay Tidake
Ranch Hand

Joined: Nov 04, 2008
Posts: 146

Hi

for that you must go for the further reading on Java introspection and reflection.
Have a look at the java.beans.Introspector class.

Thanks
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19697
    
  20

http://download.oracle.com/javase/tutorial/reflect/index.html


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Calling class methods by class object using Reflection