samedi 16 décembre 2017

Why getDeclaredMethod with Class as second param throws NoSuchMethodException?

I want to test a private method using reflection. In this case isEdible method from Food class.

public class Food {

  private Boolean isEdible() {
    return true;
  }
}

When I'm using getDeclaredMethod without specifying Food class, it ran successfully.

@Test
  public void foodTestOne() throws Exception {
    Food food = new Food();
    Method method = food.getClass().getDeclaredMethod("isEdible");
    method.setAccessible(true);
    boolean isEdible = (boolean) method.invoke(food);
    assertTrue(isEdible);
  }

But when I add Food Class on a second parameter I got NoSuchMethodException.

@Test
  public void foodTestTwo() throws Exception {
    Food food = new Food();
    Method method = food.getClass().getDeclaredMethod("isEdible", Food.class);
    // execution stop here
  }

My questions are:

  1. What should I put in second parameters to make it work? Changing getDeclaredMethod("isEdible", Boolean.class) still throws the same Exception.
  2. It seems pretty basic and intuitive, why is this happening?




Aucun commentaire:

Enregistrer un commentaire