Skip to content
Advertisement

Generics and reflection in Java. Classes

I have a task where I have to implement method of creating object of the given class.

class Paper {}

class Bakery {}

class Cake extends Bakery {}

class ReflexiveBaker {
  
  /**
   * Create bakery of the provided class.
   * 
   * @param order class of bakery to create
   * @return bakery object
   */
  public Object bake(Class order) {
    // Add implementation here
  }
  
}

How should I implement this method correctly? I tried to do it in this way

public <T extends Bakery> T bake(Class<T> order) {
        try {
            return order.getDeclaredConstructor().newInstance();
        } catch (InstantiationException | IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
            e.printStackTrace();
        }
    }

But it always throws NoSuchMethodException. Moreover, from the task “It’s guaranteed that all subclasses of Bakery will have public parameterless constructor.” And InvocationTargetException is not imported in the task so it should be implemented without it. What’s the problem?

Advertisement

Answer

This is how to do it. You have to use getDeclaredConstructor()

class Paper {
}

class Bakery {
}

class Cake extends Bakery {
}

class ReflexiveBaker {

    /**
     * Create bakery of the provided class.
     *
     * @param order class of bakery to create
     * @return bakery object
     */
    public static <T extends Bakery> T bake(Class<T> order) {
        try {
            return order.getDeclaredConstructor().newInstance();
        } catch (Exception e) {
            throw new RuntimeException("Failed to instantiate class of type " + order, e);
        }
    }

}

Usage

public static void main(String[] args) {
    Cake cake = ReflexiveBaker.bake(Cake.class);
    System.out.println(cake.getClass());
}
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement