Initialize a new object from class in Enum

前端 未结 8 510
轻奢々
轻奢々 2021-01-03 00:27

I have an Enum called Plugins:

public enum Plugins {

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


        
相关标签:
8条回答
  • 2021-01-03 01:25

    Create an interface for the plugins

    public interface Plugin{
         setShapeType();
         setX();
         setY();
         ...
      }
    

    Create a method on the enum that creates an instance of Plugin.

    public enum Plugins {
    
            ROTATING_LINE (plugin.rotatingline.RotatingLine.class),
            SNOW_SYSTEM (plugin.snow.SnowSystem.class);
    
            private Class<? extends Plugin> c;
    
            private Plugins (Class<? extends Plugin> c) {
                this.c = c;
            }
    
            // This acts as a constructor that takes args, I am assuming the args you need 
            public Class<? extends Plugin> createInstance(String shapeType,int x, int y) {
                Plugin plugin = c.newInstance();
                plugin.setShapeType(shapeType);
                plugin.setX(x);
                plugin.setY(y);
                return plugin;
            }
    
        }
    

    Instantiate in loop

    List<Plugin> myPlugins = new ArrayList<Plugin>();
    
    for (Plugins plugins : Plugins.values()) {
        myPlugins.add(plugin.createInstance(Shaped.parent, 400, 400));
    }
    

    Please note this is Psuedo Code

    0 讨论(0)
  • 2021-01-03 01:27

    There are 2 ways:

    1. use Enum.valueOf() static function, then cast it into your enum type.

      Enum v = Enum.valueOf(TheEnumClass, valueInString);
      
    2. Use class.getEnumConstants() function to get the list of the enum constants, and loop this list and get.

      Plugins[] plugins = Plugins.class.getEnumConstants();
      for (Plugins plugin: plugins) {
          // use plugin.name() to get name and compare
      }
      
    0 讨论(0)
提交回复
热议问题