2

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!

2 Answers2

7

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 invoke method instead of null):

a.getClass().getMethod("Run").invoke(a);

Note: the first call worked because you can call a static method on a null instance without causing a NPE.

assylias
  • 321,522
  • 82
  • 660
  • 783
0

you have two choices either make run() method static and remain with current call or change the current call to pass the object instance as assylias pointed.

Arpit
  • 12,767
  • 3
  • 27
  • 40