File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Beginning Java and the fly likes Very peculiar behaviour of Static method... Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Very peculiar behaviour of Static method..." Watch "Very peculiar behaviour of Static method..." New topic
Author

Very peculiar behaviour of Static method...

Chandra Bairi
Ranch Hand

Joined: Sep 12, 2003
Posts: 152
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.


Thanks,
Shekar
Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24183
    
  34

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.


[Jess in Action][AskingGoodQuestions]
 
Consider Paul's rocket mass heater.
 
subject: Very peculiar behaviour of Static method...
 
Similar Threads
5 Golden Rules of widening, boxing & varargs
Explain ouput?
overriding / overloading
Inheritance
Method invocation with null