java中的泛型和反射班级

fivyi3re  于 2021-07-03  发布在  Java
关注(0)|答案(1)|浏览(313)

我有一个任务,我必须实现创建给定类的对象的方法。

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
  }

}

我应该如何正确地实现这个方法?我试着这样做

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

但它总是不会抛出任何异常。而且,从任务中”它保证了bakery的所有子类都有公共的无参数构造函数。”并且invocationtargetexception没有导入到任务中,因此应该在没有它的情况下实现。有什么问题吗?

uqcuzwp8

uqcuzwp81#

这是怎么做的。你必须使用 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);
    }
}

}

使用

public static void main(String[] args) {
Cake cake = ReflexiveBaker.bake(Cake.class);
System.out.println(cake.getClass());
}

相关问题