• Post Reply Bookmark Topic Watch Topic
  • New Topic

How to invoke a method without arguments using Reflection  RSS feed

 
Arun Kumar
Ranch Hand
Posts: 135
Chrome Eclipse IDE Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
How to invoke a method without arguments using Reflection

I need to retrive the values from the getter methods dynamically but I couldn't find a way to invoke a method without any arguments

can any one tell me how to achieve this
 
Joanne Neal
Rancher
Posts: 3742
16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The same way as you invoke a method with arguments - Method.invoke().

From the Javadoc
If the number of formal parameters required by the underlying method is 0, the supplied args array may be of length 0 or null.
 
Nicole Lacoste
Ranch Hand
Posts: 30
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Like this...

// somehow you have an Object unknown;
Class c = unknown.getClass();
Method method = c.getDeclaredMethod("theMethodWithNoArguments");
method.invoke(unknown);

Niki
 
Jesper de Jong
Java Cowboy
Sheriff
Posts: 16060
88
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It's even easier than what Nicole suggests:

No need for the "unknown" thingy.
 
Ilja Preuss
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Jesper, what you showed was a call to a static method. The very first parameter to invoke is the object to invoke the method on, not the argument to the method.
 
Ilja Preuss
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Nicole Lacoste:
Like this...

// somehow you have an Object unknown;
Class c = unknown.getClass();
Method method = c.getDeclaredMethod("theMethodWithNoArguments");
method.invoke(unknown);

Niki


That only works since Java 5, as far as I know. In earlier version, you will need to use

method.invoke(unknown, null);

or

method.invoke(unknown, new Object[0]);
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!