Win a copy of Escape Velocity: Better Metrics for Agile Teams this week in the Agile and Other Processes forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Liutauras Vilda
  • Tim Cooke
  • Paul Clapham
  • Jeanne Boyarsky
Sheriffs:
  • Ron McLeod
  • Frank Carver
  • Junilu Lacar
Saloon Keepers:
  • Stephan van Hulst
  • Tim Moores
  • Tim Holloway
  • Al Hobbs
  • Carey Brown
Bartenders:
  • Piet Souris
  • Frits Walraven
  • fred rosenberger

Very peculiar behaviour of Static method...

 
Ranch Hand
Posts: 152
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
import java.lang.reflect.*;
public class Test
{
public static void main(String[] args)
{
try
{
Class c = Class.forName("Foo");
System.out.println("Loaded class: " + c);
Method m = c.getDeclaredMethod("getNum", null);
System.out.println("Got method: " + m);
Object o = m.invoke(null, null);
System.out.println("Output: " + o);
Foo.getNum(null,null);
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
class Foo
{
public static int getNum()
{
return 5;
}
}
consider the above code.
How could the output for this program come correctly 5. What could be reason when the getNum() method is called with null, null as parameters it is called perfectly why did this happen.
regards,
shekar.
 
author and iconoclast
Posts: 24204
44
Mac OS X Eclipse IDE Chrome
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Static methods don't need an instance on which to be invoked (hence there's no need for the first parameter of invoke() to be non-null) and your method has no arguments (hence there's no need for a non-null second parameter to invoke
The Javadoc for Method.invoke() specifically mentions that both of these parameters can be null when appropriate, and explains why. Check it out.
 
Look ma! I'm selling my stuff!
the value of filler advertising in 2021
https://coderanch.com/t/730886/filler-advertising
reply
    Bookmark Topic Watch Topic
  • New Topic