自动工厂注册 [英] Automatic factory registration

查看:49
本文介绍了自动工厂注册的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是在学习Java,而我遇到了一些问题.这里我们有简单的工厂模式:

i'm just learning java, and i meet some problems. Here we have simple factory pattern:

public class SomeFactory {
    ...
     public static void registerProduct(String name, Class<? extends IProduct > f)
}

public SomeProduct implements IProduct {
   static {
       SomeFactory.register("some product", SomeProduct.class);
   }
   ...
}

所有产品都应在工厂注册.

All products should register themselves at factory.

但是在使用此代码之前,应加载所有Products类.我可以将 Class.forName()放在某个地方,例如在main函数中.但是我想避免这种手动类的加载.我只想添加新的 IProduct 实现,而无需更新其他部分(例如 SomeFactory Main 方法等).但我想知道,是否可以自动加载某些类(例如带有注释的类)?

But before using this code, all Products classes should be loaded. I can put Class.forName() somewhere, for example in main function. But i want to avoid such sort of manual classes loading. I want just add new IProduct implementations, without updating other parts(such as SomeFactory or Main methods, etc.). But i wonder, is it possible to automatically load some classes(marked with annotation, for example)?

P.S,在运行时不会添加任何其他类,所有 IProduct 实现都在编译前就知道了.

P.S I want to notice, that no other classes will be added at run-time, all IProduct implementations are known before compiling.

UPD#1 感谢您的回答!但是是否可以使用 IProduct 实例制作自动生成的属性文件?我的意思是可以制作一些生成属性文件或加载程序代码的构建时脚本(例如用于Maven)吗?有这样的解决方案或框架吗?

UPD#1 Thank for your answering! But is it possible to make auto-generated property-file with IProduct instances? I mean is it possible to make some build-time script(for maven for example) that generates property-file or loader code? Are there such solutions or frameworks?

UPD#2 通过在启动时扫描类路径,我使用了提供运行时信息的反射库./p>

UPD#2 I finished with using Reflections library that provides run-time information, by scanning classpath at startup.

推荐答案

这是可能的,但并不容易.它将需要扫描类路径中的所有类,以查看它们是否具有注释或实现 IProduct 接口.参见如何找到以下子类的所有子类Java中给定的类?来解决这个问题.

This is possible, but not easily. It would need to scan all the classes in the classpath to see if they have an annotation or implement the IProduct interface. See How do you find all subclasses of a given class in Java? for answers to such a problem.

我会保持简单,只列出要加载的类的列表,这些类既可以在工厂本身,也可以在外部文件(例如属性文件)中.

I would do keep it simple and just have a list of classes to load, either in the factory itself, or in an external file (properties file, for example).

这篇关于自动工厂注册的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆