繁体   English   中英

使用反射进行类注册

[英]Class registration using reflection

我正在学习有关工厂模式,我使用物品作为源。 其中包含以下代码:

class ProductFactory {
  private HashMap m_RegisteredProducts = new HashMap();

  public void registerProduct (String productID, Class productClass) {
    m_RegisteredProducts.put(productID, productClass);
  }

  public Product createProduct(String productID) {
    Class productClass = (Class)m_RegisteredProducts.get(productID);
    Constructor productConstructor = cClass.getDeclaredConstructor(new Class[] { String.class });
    return (Product)productConstructor.newInstance(new Object[] { });
  }
}

我很难弄清楚createProduct()方法的工作方式。 当我尝试使用此代码时, Non-static method `getDeclaredConstructor(java.lang.Class<?>...)' cannot be referenced from a static context错误中Non-static method `getDeclaredConstructor(java.lang.Class<?>...)' cannot be referenced from a static context productClass变量已声明但从未使用过,因此代码中显然有问题,但我无法弄清楚到底是什么。 我在SO上检查了类似的问题,但不知道如何针对这种情况重新调整它们的用途。 对我来说,反思是一个令人困惑的话题。

我的问题:

  1. 此代码有什么问题?
  2. 为什么要在getDeclaredConstrutor()方法中传递new Class[] { String.class } ,这是什么意思?
  3. 为什么要在newInstance()传递Object数组而不是单个对象?

问题1

该代码有几处错误。

  1. 它只是无法编译,因为缺少cClass成员。 从逻辑上讲,它应该是productClass.getDeclaredConstructor

  2. 使用原始HashMap代替了通用类型的Map<String, Class<? extends Product>> Map<String, Class<? extends Product>> 也是ClassConstructor原始类型。

  3. 命名m_RegisteredProducts不遵守Java命名约定。

问题2

new Class[] { String.class } arg旨在使用单个String arg检索构造函数,例如public Product(String id)

它可能只是用

productClass.getDeclaredConstructor(String.class);

因为不是必须为varargs创建数组。

问题3

这个数组arg看起来像个大错。 使用String arg检索一个构造函数实例,但它传递了其他实例化它。 因此不可避免地会引发异常。

结论

在此示例中,可能在文章本身中,有太多错误或不准确的内容。 我建议选择另一个。

暂无
暂无

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

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