Here is my superclass Animal
class Animal
{
//Empty
}
My subclass Tiger
class Tiger extends Animal
{
public static void TigerPrint()
{ -------
System.out.println("Tiger");
}
public void Run()
{
System.out.println("Tiger Running");
}
}
Now I do,
Animal a=new Tiger();
At compile time a would be an Animal.At runtime it would be Tiger.
So,I did
a.getClass().getMethod("TigerPrint").invoke(null);//WORKS
a.getClass().getMethod("Run").invoke(null);//NOT WORKING (NullPointerException)
How can I call the Run method of subclass through reflection.
Yes I can do
((Tiger)a).Run();
But how can i do that in reflection!
You are invoking an instance method on a null instance – so it makes sense that you receive a NPE. Try this instead (passing an instance to the
invokemethod instead ofnull):Note: the first call worked because you can call a static method on a null instance without causing a NPE.