jeudi 16 janvier 2020

Java generics and reflection: class loading

I am given some classes that are unknown to me. Some of them are shown as an example:

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
  }

}

The task is to redesign method signature types if needed and to add implementation. The bake method should conform to the following:

  • Create objects of class Bakery or any subclass of it according to class argument
  • Flag compile-time error if order argument is not Bakery or any subclass of it (e.g. if it is Paper or Object)

Whatever I've tried I'm getting an error: Main.java:: error: incompatible types: Object cannot be converted to Cake Cake cake = baker.bake(Cake.class);

The best I've come up with is this:

public Object bake(Class order) throws Exception { return order.getDeclaredConstructor().newInstance();

I know that it's wrong but I'm completely stuck here. Could someone please explain what's going on?





Aucun commentaire:

Enregistrer un commentaire