aspose file tools*
The moose likes Java in General and the fly likes Acessing a class method Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Soft Skills this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Acessing a class method" Watch "Acessing a class method" New topic
Author

Acessing a class method

Manoj Paul
Ranch Hand

Joined: Jan 18, 2007
Posts: 112
> Let an example be like this:
>
> ******************************************************
> ***********************
>

> public class a {
> int i=10;
> public void showI()
> {
> System.out.println("Value of i = "+i)
}
> public static void main(String a[]) throws
> InstantiationException,IllegalAccessException {
> Class clazz = Object.class;
> Object oo = clazz.newInstance();
> System.out.println(oo);
> }
> }
>


> **************************************************
>
> How can i access the methow showI() using the object
> oo.
> Please tell me.
Peter Chase
Ranch Hand

Joined: Oct 30, 2001
Posts: 1970
You can't. oo is an instance of java.lang.Object.

Perhaps you can explain more about what you really want to achieve?


Betty Rubble? Well, I would go with Betty... but I'd be thinking of Wilma.
Manoj Paul
Ranch Hand

Joined: Jan 18, 2007
Posts: 112
Well i want to create an object of the class without using the new operator so that to access the showI() method.

Can you help me out?
please advice.
Ulf Dittmer
Marshal

Joined: Mar 22, 2005
Posts: 42916
    
  68
You'd use the reflection API: First, use Class.getMethod to retrieve a Method objects for "showI", then use its invoke method to call the actual method with the object oo as parameter.

Make sure "oo" is a reference to an object of type "a", not of type "Object".

It would be helpful to read the javadocs of the Class class (and the associated classes Field and Method), so that you get a feeling for all the things the reflection API can do.
[ July 03, 2007: Message edited by: Ulf Dittmer ]
Manoj Paul
Ranch Hand

Joined: Jan 18, 2007
Posts: 112
Thank you Sir,
But I dont know how will i apply this in my mentioned program...
Can you help me please?
Ulf Dittmer
Marshal

Joined: Mar 22, 2005
Posts: 42916
    
  68
There's not much to help with: create an instance of "a" (you already have that - almost), use the getMethod method of the Class object for class "a" to obtain a Method object for the showI method, and then call the "invoke" method of that Method object to actually run the method.

Which of these steps are you having difficulty with? Did you read the javadocs?
[ July 03, 2007: Message edited by: Ulf Dittmer ]
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Acessing a class method