mardi 1 décembre 2020

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?





Aucun commentaire:

Enregistrer un commentaire