Jone Bambo
Jone Bambo

Reputation: 3

Adding methods and values to existing java object

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

Upvotes: 0

Views: 35

Answers (1)

Ankur Shanbhag
Ankur Shanbhag

Reputation: 7804

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;
    }
}

Upvotes: 1

Related Questions