在枚举中从类初始化一个新对象 [英] Initialize a new object from class in Enum

查看:149
本文介绍了在枚举中从类初始化一个新对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为Plugins的枚举:

  public enum Plugins {

ROTATING_LINE(plugin。 rotateline.RotatingLine.class),
SNOW_SYSTEM(plugin.snow.SnowSystem.class);

私人类<?> C;

私人插件(Class<?> c){
this.c = c;
}

public Class<?> getClassObject(){
return c;
}

}

我想做的是通过插件中的所有枚举循环,并使用变量 c 创建新对象,如下所示:

  for(插件插件:Plugins.values()){
Class<?> c = plugins.getClassObject();
pluginList.add(new c(400,400));
}

有没有办法用类似的方法完成这个?我想要这样做的原因是在我启动应用程序时创建一个应该添加到List插件中的类的列表。

解决方案

由于您正在迭代插件,我猜所有插件的构造函数都具有相同的数字&参数类型(我不明白你的 plugins.add(...)虽然。)



无论如何,如果你想要使用枚举,我将执行以下操作,使用常量特定方法实现而不是类型令牌/反射

  public enum PluginTypes {
ROTATING_LINE {Plugin create(int x,int y){
return new plugin.rotatingline.RotatingLine(x,y);}},
SNOW_SYSTEM {插件创建(int x,int y){
return new plugin.snow.SnowSystem(x,y);}};

抽象插件创建(int x,int y);
}

public interface Plugin {
// ...
}

然后你的循环看起来像这样:

 列表&插件> plugins = new ArrayList& Plugin>(); (PluginTypes pt:PluginTypes.values())

{
plugins.add(pt.create(400,400));
}

另一方面,如果你知道你的插件的实现类,为什么不直接使用它们而不是通过PluginTypes枚举?


I have an Enum called Plugins:

public enum Plugins {

    ROTATING_LINE (plugin.rotatingline.RotatingLine.class),
    SNOW_SYSTEM (plugin.snow.SnowSystem.class);

    private Class<?> c;

    private Plugins (Class<?> c) {
        this.c = c;
    }

    public Class<?> getClassObject() {
        return c;
    }

}

What I would like to do is to loop through all the enums in Plugins and create new objects from those using the variable c like this:

for (Plugins plugins : Plugins.values()) {
    Class<?> c = plugins.getClassObject();
    pluginList.add(new c(400, 400));
}

Is there a way of accomplishing this with a similar method? The reason why I want to do this is to create a list of classes that should be added to the List plugins when I start my application.

解决方案

Since you are iterating over the plugins, I guess all plugins' constructors have the same number & type of parameters. (I do not understand your plugins.add(...) though.)

Anyways, if you want to use Enums, I would do the following, using constant-specific method implementations instead of type tokens/reflection:

public enum PluginTypes {
   ROTATING_LINE { Plugin create(int x, int y){
         return new plugin.rotatingline.RotatingLine(x,y);} },
   SNOW_SYSTEM { Plugin create(int x, int y){
         return new plugin.snow.SnowSystem(x,y);} };

   abstract Plugin create(int x, int y);
}

public interface Plugin {
  //...
}

Then your loop would look something like this:

List<Plugin> plugins = new ArrayList<Plugin>();

for (PluginTypes pt : PluginTypes.values()) {
    plugins.add(pt.create(400, 400));
}

On the other hand, if you know your implementation classes of Plugin anyways, why not use them directly instead of via the PluginTypes Enum?

这篇关于在枚举中从类初始化一个新对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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