With API7 the query method on inventory is now marked as Deprecated. For instance, if i want to get the player hotbar i had to do something like this
Inventory inventory = player.getInventory();
Hotbar hotbar = inventory.query(Hotbar.class);
This code still works in API7, however i can’t figure out how to get the same result without the use of a deprecated method like using the query method like this. So what’s the replacement for that now?
Hi Francesco_Jimi,
A PlayerInventory
has a method called getHotbar()
, so you may try the following:
PlayerInventory inv = (PlayerInventory)player.getInventory();
Hotbar hotbar = inv.getHotbar();
Hope it helps. Cheers
1 Like
The method for queries was changed in API 7 so that developers had more flexibility over the strategy used when quering an inventory (most notably for working with ItemStack
s). You can read more about the reason behind it on the PR, SpongeAPI#1610
Essentially, you have a QueryOperationType
that represents a strategy for querying something from an inventory, and this is a CatalogType
as well. In the case of the Hotbar
which is an inventory type (extends Inventory
), you’d use the following:
inv.query(QueryOperationTypes.INVENTORY_TYPE.of(Hotbar.class));
You can also use the javadocs (online or through your IDE) to your advantage. Methods that are marked as deprecated have a specific tag (@deprecated
) intended to provide information about why a method was deprecated and suggest the intended alternative where applicable. The Inventory#query(Class...)
method references Inventory#query(QueryOperation...)
. You can look at the deprecated query method to see how it’s implemented, which should point you in the right direction.
2 Likes
Thank you both, the first method worked as well, while the second one will be useful to know for sure
I would not recommend using the first method as the inventory returned by player.getInventory()
is not guaranteed to be a PlayerInventory
- that’s an unsafe cast that could throw a ClassCastException
. You should be querying for that as well in the manner described above.
Understand, will use the QueryOperationType method then