Initialize a new object from class in Enum

前端 未结 8 588
轻奢々
轻奢々 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:02

    There is a conflict in your second code snippet which confuses me a bit... the variable plugins is used both for enum constants and as a list it appears. So I am assuming this, but you should post code snippets which actually work in future.

    So, yes, there is a way to do what you want:

    for (Plugins plugins : Plugins.values()) {
        Class c = plugins.getClassObject();
        pluginsList.add(c.getConstructor(Integer.TYPE, Integer.TYPE).newInstance(400, 400));
    }
    

    Also I recommend you looking at Service Loader, which is a really cool tool to dynamically load services from the classpath.

提交回复
热议问题