Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
87 views
in Technique[技术] by (71.8m points)

How can I store Object in Enum in Java

With the Spigot-API, in Minecraft, I want to check if the Player is holding a specific Item in his hand. Can I somehow get the Item as comparative value from an Enum? I want to do that because I have some special Items with custom meta data and I want to have them in a enumeration list. Is this an eligible way? I tried something with a constructor in the enum but also I am too inexperienced in enums. -Or what would be a good way to store the items?

I just want to get the Item by doing: Items.NAME;

Would this be a solution?

public enum Items{
GRANADE (getGranade());

ItemStack item;
Items(ItemStack item) {
    this.item = item;
}

private static ItemStack getGranade() {
    //some code here
}

}

question from:https://stackoverflow.com/questions/65891415/how-can-i-store-object-in-enum-in-java

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Yes there is the Material Enum in the Spigot API, you can just use .getType() on the ItemStack to get the Material of it. But this does not include the meta data.

You could create your own enum like this:

    public enum SpecialItems(){
    ITEM1(new ItemStack(Material.ACACIA_BOAT));

    private ItemStack itemStack;
    public SpecialItems(ItemStack itemStack){
        this.itemStack = itemStack;
    }

    public ItemStack getItemStack(){
        return itemStack;
    }

}

You would get the ItemStack like this:

SpecialItems.ITEM1.getItemStack();

In the construtor you can add other values if you want to. But i think this peace of code should demonstrate probably how the concept works, otherwise take a look at the explanation of an enum by java: Java Explanation. Further, the get method should not be static beauce every enumarted thing in your enum is an object (/ an instance of the enum) and without static your method operates on the object. But the variable you want to return with the get method is only accable by the object, thus you don not want to use static in this method.

But be careful with compairing the ItemStacks of the enum and of the player hand because the ItemStack includes the amount of Items.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...