Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Acessing a class method

 
Manoj Paul
Ranch Hand
Posts: 112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
> 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
Posts: 1970
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can't. oo is an instance of java.lang.Object.

Perhaps you can explain more about what you really want to achieve?
 
Manoj Paul
Ranch Hand
Posts: 112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Rancher
Posts: 42968
73
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you Sir,
But I dont know how will i apply this in my mentioned program...
Can you help me please?
 
Ulf Dittmer
Rancher
Posts: 42968
73
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic