0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Spigot Bukkit#craftItem の奇怪な動作

Last updated at Posted at 2023-03-27

Env

Spigot API : version 1.19.2

craftItem

Bukkit#craftItem は長さ9の ItemStack の配列を渡すと、渡した配列で作成することが出来るアイテムを返してくれるメソッドである。

"Get the crafted item using the list of ItemStack provided."
Java Doc Bukkit#craftItem

とあるプラグインを作成していて、craftItem メソッドを使うことになった。
渡した配列をその後の処理でも使いまわすコードを書いたがどうにもうまく動いてくれない。
どうしてだろうと渡した配列の中身を覗いてみると全て null に変更されていた。

Player player = ~~~ ;
ItemStack[] items = ~~~ ;
ItemStack result = Bukkit.craftItem(items,player.getWorld(),player);

Arrays.stream(items).forEach(s->{
            String name = s == null ? "null" : s.getType().name();
            int amount = s == null ? -1 : s.getAmount();
            System.out.println(String.format("name : %s | amount : %d",name,amount));
        });

--- 
name : null | amount : -1
name : null | amount : -1
name : null | amount : -1
name : null | amount : -1
name : null | amount : -1
name : null | amount : -1
name : null | amount : -1
name : null | amount : -1
name : null | amount : -1

インターフェースまでは追跡することが出来たが、実装クラスのコードを覗く方法が分からなかったので、どういう経緯により配列の中身が真っ新になってしまったのかを突き止めることはできなかった。

対応

craftItem へ渡す前に配列をクローンしておく。

ItemStack[] send = ~~~ ;
ItemStack[] copy = send.clone();
ItemStack result = Bukkit.craftItem(send,player.getWorld(),player);
Arrays.stream(copy).forEach(s->{
            String name = s == null ? "null" : s.getType().name();
            int amount = s == null ? -1 : s.getAmount();
            System.out.println(String.format("name : %s | amount : %d",name,amount));
        });

---
name : OAK_LOG | amount : 2
name : AIR | amount : 1
name : AIR | amount : 1
name : AIR | amount : 1
name : AIR | amount : 1
name : AIR | amount : 1
name : AIR | amount : 1
name : AIR | amount : 1
name : AIR | amount : 1

OK.

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?