0

I'm trying to add a function that add a unique id to an object in java. I've a function that returns me an object:
ItemStack is=ent.getKiller().getItemInHand();
I made a java class that extends ItemStack class and i tryied to cast the object to this class.

import org.bukkit.inventory.ItemStack;
import java.util.UUID;
public class UniqueItem extends ItemStack{
    private String uid="";
    public UniqueItem(){
        uid=UUID.randomUUID().toString();
    }
    public String getUniqueID(){
        return uid;
    }
}

UniqueItem is=(UniqueItem)ent.getKiller().getItemInHand();

It produce me an error and i don't undersatand why. Please help me to solve my problem or give me an alternative solution.
Thanks

2
  • What is the error message? Commented Nov 15, 2015 at 11:52
  • ItemStack is not a UniqueItem, thus you cannot cast it that way around. But UniqueItem is a ItemStack and you can cast UniqueItem to ItemStack Commented Nov 15, 2015 at 12:30

1 Answer 1

1

You get a ClassCastException at runtime because you are trying to cast an item which is not of type UniqueItem

Also, extending the class will not help you. Instead create a wrapper class around ItemStack object which maintains unique ID along with the object.

Try this:

// wrapper class
public class UniqueItem {
    ItemStack item;
    private String uid="";
    public UniqueItem(ItemStack item) {
        this.item = item;
        uid=UUID.randomUUID().toString();
    }

    public String getUniqueID(){
        return uid;
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.