简体   繁体   English

Generics 和 Java 中的反射。 课程

[英]Generics and reflection in Java. Classes

I have a task where I have to implement method of creating object of the given class.我有一个任务,我必须实现创建给定 class 的 object 的方法。

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.但它总是抛出 NoSuchMethodException。 Moreover, from the task "It's guaranteed that all subclasses of Bakery will have public parameterless constructor."此外,从任务“保证 Bakery 的所有子类都将具有公共无参数构造函数”。 And InvocationTargetException is not imported in the task so it should be implemented without it.并且 InvocationTargetException 未在任务中导入,因此应该在没有它的情况下实现它。 What's the problem?有什么问题?

This is how to do it.这是如何做到的。 You have to use getDeclaredConstructor()你必须使用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());
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM