#help-development
1 messages · Page 1876 of 1
how can i set that to an anvil
Don't try
Anvils are the most evil thing in existence, I have spent far too long debugging those only to come to the conclusion that they are far too evil
Not possible without setting a second input item and hoping the server owner has the right server software
bruh
You can force-set an output item but under certain impls the user will not be able to take it
Under other conditions the player will not be able to take it regardless of whether spigot or paper is used (didn't test anything else yet), even if the player sees that it can take it
Anyways, in theory it is doable via setting the output of PrepareAnvilEvent#setResult
maybe i can just empty the 2nd slot
You could also perhaps mess with subtly renaming the item, but I have not tested that yet
It might also be worth checking whether anvil.setItem(3, itemstack); is doable, I haven't checked that either, though I fear it might have a few drawbacks
How do bot attacks work? I've seen a couple and want to experiment with a protection plugin. I understand nobody is going to help me cuz that would be stupid, but what would be a good direction? Is it mostly done with an application or smth?
hard to imagine 100 different players joining yk
If I'd would want to DOS a server I'd spam the join request while sleeping for a relatively long time between responses between the steps of the join procedure, but I think newer versions of vanilla minecraft kinda make this hopeless to pull off
Hello, i coding with the spigot 1.12.2 API and i have a NullPointerException from if (event.getItem().getType() == Material.FEATHER) when i click rightclick on block.
Why is this
I use Java 8 is this the error?
No, but Java 14+ will tell you exactly what is null so you don't have to ask a human about it
And why is this error?
Plus Nullabillity annotations would tell you that really only event.getItem() or event can be null; second one is unlikely, so it is the first one
Itemstacks are often null if they represent Air. Blame Bukkit for being decades old
I rightclick with feather not with air
if (event.getItem().getType() == Material.FEATHER) { isnt wrong???
Not knowing what event is, event has to be null then
event is PlayerInteractEvent
hm, they didn't use nullabillity annotations back then.
It could be possible that it is generating two events, one for the on-hand and one for the off-hand
But its working with event.getMaterial() thanksss#
isnt it event.getClickedItem()?
how do you create a dyed shulkerbox itemstack?
like what part of the data would you have to grab to modify the dye value?
i see that the ShulkerBox interface has a getColor() method but no setColor() method
I have a new Null Pointer on if (player.getInventory().getChestplate().getType() != Material.ELYTRA) {
there's nothing in the chestplate slot
The ShulkerBox interface is for the block not the item, As for set the color.. each shulker box color is a diferent item so use something like Material.getMaterial(dye.name() + "_SHULKER_BOX");
how do u get an entity player is looking at
thanks
i was using blockstatemeta to set the itemstacks itemmeta which is why i was looking at the block interface
public class Grief implements Listener {
@EventHandler
public void onBlockBreak(BlockBreakEvent event) {
Material type = event.getBlock().getType();
if (!type.equals(Material.OBSIDIAN) &&
!type.equals(Material.CRYING_OBSIDIAN) &&
!type.equals(Material.RESPAWN_ANCHOR) &&
!type.equals(Material.COBWEB) &&
!type.equals(Material.GLOWSTONE)) {
event.setCancelled(true);
}
}
@EventHandler
public void onBlockBreak(BlockPlaceEvent event) {
Material type = event.getBlock().getType();
if (!type.equals(Material.OBSIDIAN) &&
!type.equals(Material.CRYING_OBSIDIAN) &&
!type.equals(Material.RESPAWN_ANCHOR) &&
!type.equals(Material.COBWEB) &&
!type.equals(Material.GLOWSTONE)) {
event.setCancelled(true);
}
}
@EventHandler
public void onItemDrop(PlayerDropItemEvent event) {
event.getItemDrop().remove();
}
@EventHandler
public void onEntityExplode(EntityExplodeEvent event) {
Bukkit.getPlayer("Dacaly").sendMessage("Entity Explosion");
event.blockList().clear();
}
@EventHandler
public void onBlockExplode(BlockExplodeEvent event) {
Bukkit.getPlayer("Dacaly").sendMessage("Block Explosion");
event.blockList().clear();
}
}
First 3 events works, but both entity and block explode don't even fire when exploding tnt
i'd make an enumset for the materials
Cancel the event
and use #contains
And yea, that
is that only for creaper? imagine...
I registered both
Nvm im blind
Lol
Hey, can someone give me a link to md5's non flickering scoreboard?
Entity? Maybe end crystal?
Or wither, idk
Creeper, tnt, end crystal, tnt minecart, ghast fireball, wither
uhm so, cancelling the event will also cancel dmg
Yes...
I'm basically making a pvp server
With end crystals and stuff
So I want to disable all blocks being broken
Wg
Just clear the block list them
Oh that actually works?
Lagged my server
And it's not necessary if I can make my own little version
Instead of listening to 30 events
Does work, thx
Thought would be defensively programmed
Hello, I want to get an entity that player is looking at, how can I do it?
could go though all players in the world, and then do some sort of hitscan
World#rayTrace
what would it return
?jd
very cool
probably a raytrace result, specifying the hit entity or tile
okay and the vector will be player eye location?
helps me understand stuff
it also gives me source code later
so i can modify it and then compile
- intellij decided to not start up 🙂
mm whatever
but yeah just ray trace it
gotcha, do i need ray size and filter or na
depends how far you want it
isnt max distance for it?
ill limit it anyway
cuz i dont want players to interact with entities like 100 blocks away
basically what im doing is
when player clicks f and looks at item frame, it will open a spray gui
Hey guys, I'm having a problem with Chunk#getEntities in ChunkLoadEvent
It only contains the mobs that are obviously there the second time I join
So when the server restarts and I join, it is missing a mob that is there, but when I rejoin again it works
class org.bukkit.util.RayTraceResult cannot be cast to class org.bukkit.entity.Entity i am getting this, how to get an entity from raytraceresult?
getHitEntity()
thanks
Alright I found out that ChunkLoadEvent is not called for the chunk the player is in the first time he joins
But why?
hey, can regular chatcolors be used in TextComponents? (I'm asking bc there's a method called setColor)
could someone give me an example snippet of getting player eye vector?
Player#getDirection
bunp
Because Minecraft keeps the spawn chunk loaded unless you tell it to do otherwise, so it’s not loading in when the player logs in, it’s already loaded
Yeah I also understood that now, just added PlayerJoinEvent to it
But thank you!
Allright thanks!
but you cant override the methods
Ah
Sos hum
Big problem
Because i need to implements methods from interface/abstract class. One of them yes or yes should be static
dont make the method static 😊
But if i dont use it. Every new Menu() clear my menus, so my menu api doesnt work. Because the menus are not being registered. Because im creating an instance everywhere
Do you understand i refer to?
yes
So i dont know how to do it
Hum i will have to recode. In some way of having an interface/abstract class with a static method (that could be override)
Any ideas?
Right thanks, Drive carefully please
back to the ray trace entities, for location do i use player location or player eye location
yes
Which of the options. Its no a yes/no question. BTWWW
well looks like when tracing it only traces me
Does anyone know how to get the highest block in worldgen population, because
location.getWorld().getHighestBlockAt(location);
doesn't work because world is always null.
yeah only i get logged
so how would i go about making a block that cant be broken faster with any tool? is there a way to do this?
With Maven shade plugin its possible to relocate a class to another package?
Allright thanks
Does anyone know about block populators, because since 1.17 I have not been able to find out where the highest block is, e.g. to place a tree there.
pls help
how could I execute a command through my plugin?
For example: I (as an in-game user) send "/execute give @p diamond 1" and my plugin makes the server execute the command "give @p diamond 1"
Same lol I remember finding it a while ago but I can't remember it at all not even to search it up
oh yeah ty I remember now
Like this I think (?) xd
Bukkit.dispatchCommand(plugin.getServer().getConsoleSender(), "command");
oh yeah lol that is the same as plugin.getServer...
No i think
oh lol why?
I think its just Bukkit.getConsoleSender()
well according to eclipse, both of them return ConsoleCommandSender which I guess is instance of CommandSender (the first arg needed for dispatchCommand())
idk if there's a difference between the obj returned by each
how can i ignore certain entity type in world#raytraceentities
bye (: ty
just enter a predicate that returns false if it is a type you want to ignore
or one without double raySize
also available, just missed it
Is it possible to convert the ChatColor of Bungeecord to the ChatColor of Spigot or to set a custom color code in the Scoreboard Team.setColor?
If i opened a custom inventory to a player using player#openInventory(). When doing player#getInventory() will return the object of my custom inventory or his inventory?
I dont think its possible to use custom colors in scoreboards
I think there was a way to convert it
Let me search
And which one would that be? because ChatColor from Spigot is an enum
If it is just a normal chatcolor, maybe try something like
org.bukkit.ChatColor.valueOf(myBungeeChatColor.getName());
fixed it
i try it
When i fix this. I wil ltry to make a method for doing that
players inventory
so like the hotbar and stuff
not the open one
no, that gives me an java.lang.IllegalArgumentException
you can use Player#getOpenInventory()
is your bungeecord chatcolor a custom or default one
custom
😦
Ah, thats explain why when using my custom menu systen. And click on my inventory detect as i where clicking on the menu i oened
I can try to make one. But be patient
Sure gladly!
its just simply not possible
bukkit chatcolors dont support custom color codes
its an enum
Custom?
even with reflection
Expalin that
html colors
Ahh i think he want to convert the default bungee colors. To the spigot ones
he has a net.md_5.bungee.api.ChatColor.of(Color)
Spigot has it too
yeah using my code
org.bukkit.ChatColor.valueOf(myBungeeChatColor.getName());
should work
or myBungeeChatColor.name()
Oh i will add that one to my lib. Do you have any problems?
i dont know for sure
I refer to you because im going to do it open source them
you need an inventory view
Ah
Allright
And for open it, as well i will need to open it as an InventoryView right?
Ok thanks
Yeah
yeah you dont need inventoryview to open it
The problem is this. When i open my menu and click on the custom nenu its sent the debug message. And when i click outside the custom menu (player ivnentory) it send the debug message aswell
since Inventory interface does not have a method to get InventoryView, you can not access the view without an InventoryEvent
Hyperion
it already returns an inventoryview
HumanEntity#getOpenInventory()
use getTitle()
I cannot use player object?
Its an extend i think
player.getOpenInventory().getTopInventory().getName()
getBottomInventory() will return the players inventory
This should return the name of the custom inventory right?
it doesnt have a name
no use player.getOpenInventory().getTitle()
This i want to solve
Ah ok
but it does contain color codes
yes
My custom menu title can contains color codes
I save it on my manager (map<>) with the color codes already
Compare the inventory instance not its title.
Hem??
yeah thats a better approach
Omg im confused
if (view.getTopInventory() == <inventory expected>)
Its posible to force close a custom menu?
Thanks
player.closeInventory()
But i need to check if the menu exists so that way wont fit
what
?paste
it will return false if the inventory is null
so no need to check
if thats what you mean
I send code and explain what i want to do
^ use this
just paste your code, click save, copy the url and paste and send it here
Is it possible to stop carpet from being removed by water?
yeah but i cant find an event which would solve this xD
@EventHandler
public void flow(BlockFromToEvent event) {
// get block
Block to = event.getToBlock();
// check for carpet
if (to.getType().name().contains("CARPET") {
// cancel
event.setCancelled(true);
}
}
@silent stratus try this
ok thx
when you have a gui opened and you open another one does the old one stay opened?
what
i dont think so
you cant have two guis open
okay so it closes automatically
so then why the hell my thing looking through the old gui that doesn't exist
whatt
i dont know?
what are you trying to do
if you are using Player.getOpenInventory().getTopInventory() it should yield the new one
no
?
im just opening the inventory
Works fine! Love You
xD
np
i think you can just always cancel it to prevent water from destroying anything
but i dont know 100% sure
ok
oh no wait
so before this code when an item is clicked it opens a new inventory then here im checking to see if an item was clicked in the new inventory but for some reason its looking through the old one if (((InventoryClickEvent) event).getCurrentItem().getItemMeta().getDisplayName().contains("Autoban")) {
make sure to check if the destination block (event.getToBlock()) isnt air
otherwise it will never flow
not even into empty blocks lol
ok thx
how do you know that its looking through the old one
because I debugged it
how
like external memory poking tools
no
or System.out.println("a")
but how do you check which inventory its looking through
because if just this check is not working then it may be because the contains() fails
because I checked if it contains one of the other things in the old inventory and it's returning true
I even tried closing the inventory before opening new one
ClassNotFoundException: com.mongodb.MongoClientSettings
this happens when trying to setup a client for MongoDB
private MongoClient client;
// ^ in the scope
MongoClientSettings settings = MongoClientSettings.builder()
.applyConnectionString(creator.get())
.build();
client = MongoClients.create(settings);
even though MongoDB core and driver is implemented into my project
then use the shadow plugin
link maybe?
plugins {
// ...
id "com.github.johnrengelman.shadow" version "7.1.2"
// ...
}
add this
into the plugins block
the id thing
okay
and then run shadowJar instead of jar
under a new shadow catagory i think
or under build
uhh wait
?
kotlin dsl?
ye
plugins {
// ...
id("com.github.johnrengelman.shadow") version "7.1.2"
// ...
}
use this instead
ok thank u
np
so i use shadowJar instead of jar when building ye?
here is some code ```java
if (((InventoryClickEvent) event).isLeftClick()) {
if (((InventoryClickEvent) event).getCurrentItem().getType() == Material.BOOK_AND_QUILL) {
if (user != null) {
GUICommand.settingsInventory(user);
if (((InventoryClickEvent) event).getCurrentItem().getItemMeta().getDisplayName().contains("Autoban")) {
i use that instead of the normal jar ye?
yes
please make a variable for (InventoryClickEvent) event
yo wtf thats like 10x the size of the original one
this is nearly unreadable
yep
oh wait it might be shadowing the spigot jar
do you have it on compileOnly?
the spigot dependency
bro im sure writing (InventoryClickEvent) event 10 times takes up more time than writing InventoryClickEvent ev = (InventoryClickEvent) event;
ye
im using paper
all I need to write is event and it casts it for me
ur also casting it three separate times
compileOnly("io.papermc.paper:paper-api:1.18.1-R0.1-SNAPSHOT")
ohk then its just a lot of libraries
yeah thats fine
dont worry
aight thank u so much u saved me alot of time to waste online
i alr wasted the entire day
np
i really appreciate this
oh shit
it was the same thing for me
Which is fine
for some reason i couldnt figure out how to do that
oh well
first time is a first time ;-;
yeah lmfao
nice
okay i will now attempt to decipher this
Repeating xode is alwqys bad
that doesnt give me enough context still
If you want to change something, you'll have to change it in all places as well
and btw it is in a variable
ok wait
i need to know how you are checking it and opening it
like checking which inventory its 'scanning'
yeah
especially when you need it in a statement directly
((Class) e)
horrible
Exactly
bye
trycatch
acceptable
java cast aint that bad
try c++ cast
static_cast<InventoryClickEvent>(event)
What do I have to do to log messages into console like:
[ERROR]: Something happened lol
?
Logger logger = Bukkit.getLogger(); logger.info("Woa, a log");
At least thats how I do it
Like this:
plugin.getLogger().log(Level.ERROR, "Something happened");
?
Use: plugin.getLogger().severe("text"); -> that what i use
Your werlcome
everyone uses a different thing xD
That link? Hum - i can smell smth strange
?
I mean any of what we said
Make sure code is fully up to date
look at the way it is just continuing if statements even though they are false
This manages the string like a message? I mean can I use ChatColor.translateAlternateColorCodes()?
I am losing my mind
Yes
alr ty
I recommend for that creating a method similar to this: public static String style(String text) { return ChatColor.translateAlternateColorCodes('&', text); }
Agreed
So you forget about using ChatColor.translate every where
yeah lol I actually remember seeing yours way before online but I didn't remember it, @sterile token's way looked simpler so I use that heh
yup literally have that hahahah
import org.bukkit.ChatColor;
public class Utils {
public static String color(String str) {
return ChatColor.translateAlternateColorCodes('&', str);
}
}
xd
hahah yeah
Yeah I have a class thats whole purpose is so I can do CC.translate("&cCOLORS");
One of the essentials
thats fair
And i have another one if you want to implement:
public static List<String> style(List<String> text) { return text.stream().map(Chat::style).collect(Collectors.toList()); }
okay you were right holyshit
This is my previous thingy
public class General {
public static String colorize(String str) {
return ChatColor.translateAlternateColorCodes('&', str);
}
public static String colorWithPrefix(String str) {
return ChatColor.translateAlternateColorCodes('&', Main.pluginPrefix + " " + str);
}
public static int randomize(int min, int max) {
Random ran = new Random();
int result = ran.nextInt(max+1)+min;
return result;
}
}
I have been trying to fix my code and it hasnt updated in 30 min cuz it compiled into the wrong folder
yeah well idek what does that do XD
it for translating a list of messages with color char
Does that style a list? thats cool
Yeah
I was right lesgo
and its effecient, thats amazing
non of that looping through each of the strings BS
oh nice
Any aproah about sending messages in this way:
new Message().message("[Command] Menu " + menu.getName() + " for " + player.getName() + " has been opened").sendMessage(player);
??
Literally what I'd do :sadge:
you could simplify that with a static util
Me?
ye
you have ++i rather than i++, not sure if this will make a difference tho
agreed
I'm just begginer 😦
Personally instead of sendMessage I would just broadcast it to everyone so you remove a loop
do: Bukkit.getOnlinePlayers().forEach(player -> player.sendMessage("bla bla"));
^^
It less code and i think its more efficient (confirm please)
or just Bukkit.broadcastMessage("stuff"); Not like 1 foor loop is gonna make a big difference either way
that also broadcasts to console tho I think
Oh yeah fair
yeah def do what VERANO said then
confirmed
Rack and rock are you experimented with guis/custom menu?
Cuz im coding a custom api for doing it easly but i need some recommendations
GREAT, I love GUIs, I made a simple wrapper in the past but yeah sure ill help
Oh thanks!!
Of course!
Can i send paste code?
Sure
Wait i will test the recode. Because i made one. And now i recode it. Because lot of things were not working
Yeah
public JSONObject getJsonValue() {
JSONParser parser = new JSONParser();
FileReader reader = new FileReader(file); // this had try catch to it aswell in the code but i removed it for explaination here
Object o;
try {
o = parser.parse(reader);
return (JSONObject) o;
} catch (IOException | ParseException e) {
e.printStackTrace();
return null;
}
}
I have this to parse json text to JSONObject but everytime i try to call this method it just clears the file for no reason
the file becomes empty everytime i try to call this
and it throws
[WARNING] .... Unexpected token END OF FILE at position 0.
[WARNING] .... at org.json.simple.parser.JSONParser.parse(JSONParser.java:257)
[WARNING] .... at org.json.simple.parser.JSONParser.parse(JSONParser.java:92)
because you were making a FileWriter yesterday werent you
in your fields
making a new FileWriter will clear the file
but I've already told you that your code is shocking; and you haven't explained why you need json
i need json because ive never used it, everyone of my friends are talking about it and would like to have new experience
but what is really bad about my code? i know i am still a beginner but what is bad? everyone says its bad but never why?
also thanks for telling me about Writer thing ima fix it
im working on an smp plugin that involves the use of json atm
Okay so I am using PlayerInteractEvent but I only want to run code when they interact like trying to open a door or chest, not just interacting with any block. Do those type of blocks come in a bulk or something or is there way to check that or I gotta specify all of them?
so I would have to check for every instance? Check if it is a door, chest, shulker, etc... ?
I said like a chest and door as an example but I mean every block that has like a special function. I want to send a message if a player is interacting with one of those special blocks
declaration: package: org.bukkit, enum: Material
Which is the hashmap functions to get and object and if it doesnt exists, it add to the hashmap?
Thanks
I think there is a function just for that actually
computeIfAbsent
Thanks
putIfAbsent
It take 2 parameters right?
yeah
just compute does
the computeIfAbsent is a higher order function which takes a function with 1 param iirc
When I click Implement Methods for a CommandExecutor class, the onCommand() method looks like this:
@Override
public boolean onCommand(@org.jetbrains.annotations.NotNull CommandSender sender, @org.jetbrains.annotations.NotNull Command command, @org.jetbrains.annotations.NotNull String label, @org.jetbrains.annotations.NotNull String[] args) {
return false;
}
How can I prevent IntelliJ from adding @org.jetbrains.annotations.NotNull automatically?
May I ask why you don’t want them there x)
I was gonna ask the same
It gives me 4 errors
What are the errors?
Oh you haven’t imported the library perhaps
jetbrains annotations library probably
how do I import it? and what does it do?
ye
You can hover over the @NotNull and click the import option I think
Do you use maven or gradle?
ah
maven
Yeah Well might be the case the library isn’t present at your compile time classpath
Or add this to the top
import org.jetbrains.annotations.NotNull;
I think at least
although what's the advantage of having it/what does it do?
Well if you don't have the lib you can't import it.
It's great for annotating methods for if they have the possibility of returning a null value. Great if other people are working with your code.
I assumed it just wasnt imported but I might just be misunderstanding
In principle nothing
But if you’re a disciplined developer
It will help you to determine Nullable types
It won’t guarantee anything
But yeah
Ok
Yeah it's less useful if you're working alone or on code that no one else will see but it helps if you leave a project and come back.
The problem is that for instance intellij will assert that anything with that annotation might be null/or never null, which is a bit false as you can still pass null to @NotNull for instance. It’s equally helpful for solo projects as well as team projects imho.
How would be to get all class object that are annotated with a custom Annotation (Using reflections package from java) ?
The annotation must have retention set to runtime
Is it possible to edit tab completer in existing minecraft command? like summon, kick etc
Yes i already have that declare on my annotation class
Then checkout AnnotatedElement
Stuff like Method, Constructor, Field, Class derive it
But the annotation wont be on a method/contruscturo. It will be on top of the class name
Like this
Yeah should be
Yeah verano
Then use Class::isAnnotationPresent
Please an example
Ahh ok
And Class::getAnnotation
Thanks
(It has a type parameter which will help you with casting it to your annotation type)
didnt understand
so how? i tried with PacketPlayInTabComplete and PacketPlayOutTabComplete but that doesn't work with minecraft commands for me
Unrelated to the annotations stuff, but I'm getting this error https://paste.md-5.net/yuhumopobo.cs and can't find anything useful online. I'm not extending JavaPlugin twice, and I don't have the plugin installed twice either.
My main class:
public final class BLDiscord extends JavaPlugin {
@Override
public void onEnable() {
// init default config
getConfig().options().copyDefaults();
saveDefaultConfig();
getCommand("discordsyncreload").setExecutor(new BLDiscord());
Bukkit.getPluginManager().registerEvents(new ChatEvent(), this);
}
}
Chat listener class: https://paste.md-5.net/urexatiyum.java
Reload command class: https://paste.md-5.net/fucoheluje.java
webhook class: https://paste.md-5.net/iqujofuyop.cpp
Verano the T there is a type parameter
Maybe just inject nms? Or overlap the native cmds with a Bukkit command
Like that conclure?
I want something more specific
.
What does the error say
required type int
maybe try contains instead of get?
I can do a singleton pattern via annotations?
I want to something like Spigot service
Spigot service?
Wait i explain my diea
bump 😄
use this instead of new BLDiscord()
how can I change what the player said using AsyncPlayerChatEvent?
Because new BLDiscord() creates a new object (this does not)
setMessage iirc
i tried that but all it did was print it out to the console
Wat
I want to annotate classes with custom annotation. When plugin init it will loop all clases and then save their instance. So i dont have a mess on main class with:
private Classname class;
public void onEnable() {
this.class = new Classname();
}
public Classname getClass() { return this.class; }
Do you understand my idea?
Sounds strange
and it printed to console
To me or to him?
Not you
Ah ok
Verano if you want a dependency injection framework checkout guice Ig
I just tested it, nothing happens when I do the command. the reload command is in a separate class called ReloadCommand, not the main class.
I need to go to sleep now but maybe verano can assist you KickSquare
Allright
Can i tag him?
thanks for all the help 🙂
set the executor to a " new <NameOfCommandClass>()"
do you have any other ideas?
Can you help me with dependency injection? I want to a simple framework. So i dont have a mess on my plugin class. With creating the instance and then the getter
giving me this error
sorry, I don't really know much about that
using getCommand("discordsyncreload").setExecutor(new ReloadCommand());
well then supply the parameters to the constructor?
extension methods in kotlin are basically just static methods and can only be accessed from the same kotlin class right? Like e.g.
class Test: JavaPlugin() {
fun Player.sendColoredMessage(message: String) {
sendMessage(ChatColor.translateAlternateColorCodes('&',message));
}
}
is the same as
public class Test extends JavaPlugin {
static void sendColoredMessage(Player player, String message) {
player.sendMessage(ChatCOlor.translate.....);
}
}
with the downside that the kotlin version can only be used in the same class right?
worked, tysm :pes_party:
is there a way to check if the getItemMeta gives you a meta of type UNSPECIFIC_META
I can only think of checking all subinterfaces. but why would you ever to check it?
cuz im causing a crack with item meta i believe
you could just serialize the itemmeta to see what it is, but that's pretty useless because tbh you will never need it
why cant i post screenshots sadge
you could also get the ItemMeta's classes annotations
declaration: package: org.bukkit.configuration.serialization, annotation type: SerializableAs
because you're not verified
this is my problem ^
use ANY other website pls
prnt.sc is the worst screenshot website
reload
but i am verified now anyway so
here
that is an itemstack without meta
but why does it say null
because the ItemMeta is only created when it is needed
that's the source of ItemStack#getItemMeta
what do you mean?
does someone know why only my java classes are compiled but not my kotlin classes? https://paste.md-5.net/lumuzajipa.xml
why not? when it's not renamed, it has no displayname
so "Diamond Sword" is standard and gets not saved to displayname
cause no name change
anyway getDisplayName() is annotated with NotNull so it actually should NEVER return null
yeah but it just did lol
what's your code?
yeah it doesnt check if it has displayname
ill add that and it should resolve the issue
weird thing to have @NotNull but still have "Should check that hasDisplayName returns true"
that is kinda contradicting
yeah no idea lol
its called a bug
though really it should throw an exception
but that would screw up too many plugins nowadays
in what class is getDisplayName actually implemented?
I only found in ItemMeta where it's declared but not implemented
CraftMetaItem
aaah thx
uh
hm I can't find that class
the code doesnt look like it will return null to me
what spigot version are you on
md_5?
1.12.2
idk what version of spigot that actually is
1.12.2 didnt have nullable annotations though???
not my screenshot
that might be the reason lmfao
documentation of something more recently
it should really return "" in 1.18
how can i spawn slime with negative size? i tried with reflections but it doesn't work for me
EntitySlime slime = new EntitySlime(EntityTypes.aD, worldServer);
slime.setPosition(location.getX(), location.getY(), location.getZ());
slime.setNoAI(true);
try {
final Field size = EntityInsentient.class.getDeclaredField("bK");
size.setAccessible(true);
size.setInt(slime, -2);
} catch (NoSuchFieldException | IllegalAccessException e) {
e.printStackTrace();
}
worldServer.addEntity(slime);```
what would happen with negative size aint that kind of impossible
slimes can only be between 1 and 127 size
in 1.12.2 getDisplayName() i's not annotated with NotNull and CraftMetaItem simply returns this.displayName there
well guess what, 1.12.2 aint getting bug fixes
poor 1.12
1.12.2 sucks
I like it
Something related with reflections.
When class:
A extends B
The code: will be true?
A.class.isAssignableFrom(B.class)
no, otherway around
B (the parameter) is a super class / superinterface of A, so B is assignable from A
Determines if the class or interface represented by this Class object is either the same as, or is a superclass or superinterface of, the class or interface represented by the specified Class parameter.
mfalex
Can you help me?
Im going to create a Service.class that every service will extend right?
I have a Set<Service> and a method with: Service get(Class<?> clazz) how can i check if the Set contains that class?
set.contains(clazz) ? 😄
Is this method okay?
to check if it contains it
boolean isPresent = mySet.stream().anyMatch(service -> {
if(service.getClass().equals(clazz)) {
return true;
}
return false;
});
/**
* Returns the given Service by it's class or null
*/
private Service get(Class<? extends Service> clazz) {
return mySet.stream()
.filter(service -> service.getClass().equals(clazz)
|| service.getClass().isAssignableFrom(clazz))
.findAny().orElse(null);
}
I'd do it like this
I created a class with the pupourse of implement it on every service, so them i can do:
Service.get(ServiceTest.class).methodFromServiceClass()
But it not possible
show your service class pls
right
and one of the implementations
right
ServiceHandler -> Will be extended by every service
ServiceTest -> A service
Service -> The services manager
there
When running a task with a delay should I do it asynchronously?
ugh do you know how interfaces work?
you haven't declared any method there
oh wait sorry
I didnt see the third screenshot
but
still
Service should have a method, probably abstract, called enable()
ServiceTest must extend Service
and Service should be either an abstract class or an interface
I want to do it back way around. I want get the methods from the TestService from ServiceHandler
And the serivehandler cannot have the methods
then declare them in ServiceHandler
You can
you just write public abstract void enable(); inside
ait i will use the translator
anyway your naming is messed up too
the ServiceHandler (probably meant to be something like Bukkit's PluginManager) is the class that should handle registering your Services
and the Service class should be an interface or abstract class that declares the methods your actual Services should override
Look, I want to make a system that records a class. And that I then by means of a get(ClassName) can obtain the class instance and then can use the methods. The problem is that each service can have the methods it wants. They will not be predefined from the interface. That's my problem
so TestService should either implement or extend Service, not ServiceHandler
Now its clear?
Well but if you already have the services' class, why now just cast your Service object to it's specific class?
He?
I didnt understand
Am I not able to use Hex colors to set the Team#setColor
Can you show a real life example on what you want to do with your code?
But would i be able to do: Service.get(ClassName.class).enable()?
Why is that
Because its not supported
not implemented yet or just mojang restricting it
make Service.get return an instanceof your interface that declares an enable() method
in spigot or in minecraft
An example?
No no
you are not understanding
well you are not understanding too
Btw
you want all your services to have an enable method, otherwise this code makes no sense
so that method should be declared in the interface
of course the implementations can have additional methods
No, i want every service be able to have the methods you want. Not pre defined method
I understood this the whole time
So why you said that i want to implement pre defined method on every service?
When i want the opposite
So can you give an idea of how i can do it?
because you wanted to call enable() on a generic Service and not a special subclass
public abstract class Service {
void enable() {
}
}
public class TestService extends Service {
@Override
public void enable() {
// Enable logic
}
public void doTestStuff() {
// Do test stuff
}
}
public class SomeOtherService extends Service {
@Override
void enable() {
// Enable logic
}
public boolean yeeha() {
return true;
}
}
My class Service wont have methods
there is no sense in defining ANY interface or superclass if those classes are not meant to share at least ONE method
Ahhh
then you don't need any Service class at all
Set<Object>
1- Register a class
2- Set the instance and save it (until the plugin disable)
3- And get the methods from the service
In other words i want to be able to do that
I think I explain myself for the ass
how would you know what methods it has? I don't see ANY real life example on why you would need to store totally unrelated class instances that do not share ANY methods inside the same set. I mean - what are you going to do with them?
so you have something like this
public abstract class ServiceHandler {
Set<Object> myServices = new HashSet<>();
public Object get(Class<?> clazz) {
// return the Object that belongs to this class
}
}
for what do you ever want to use it?
Object object = ServiceHandler.get(SomeClass.class);
// Now what? You have no idea what this object is unless you cast it
My goal is to stop doing this with every class on my main plugin:
private Class1 class1;
private Class2 class2;
public void onEnable() {
this.class1 = new Class1();
this.class2 = new Class2();
}
public Class1 getClass1() { return class1; }
public Class2 getClass2() { return class2; }
Now you understand?
Records are crying out
well you can of course do something like this:
Like what?
Set<Object> static myServices = new HashSet<>();
public static <T> T get(Class<T> clazz) {
return clazz.cast(myServices.get(/* The logic you already have*/))
}
whops
the static keyword is at the wrong place
static Set<Object> myServices = new HashSet<>();
public static <T> T get(Class<T> clazz) {
Optional<Object> result = myServices
.stream()
.filter(object -> object.getClass().equals(clazz) || clazz.isAssignableFrom(object.getClass()))
.findAny();
return result.map(clazz::cast).orElse(null);
}
Although this is horrible and I have no idea why you would ever need sth like this 😛
Or use this instead of result.map:
return result.isPresent() ? clazz.cast(result.get()) : null;
You can then do MyCustomObject custom = get(MyCustomObject.class)
If you move an item from your players inventory to an (in my case) custom inventory how do I get the moved item? (its not event.getCursor() nor event.getCurrentItem() and also not bag.getItem(event.getSlot()) (InventoryInteractEvent)
Using the number buttons
so move item 1 with tapping 1 and hovering over the selected slot to move to
Never use InventoryInteractEvent, use InventoryClickEvent
why?
Because InventoryInteractEvent its an abstract class
oh it actually is an inventory click evnet my bad
@sterile token
import java.util.HashSet;
import java.util.Optional;
import java.util.Set;
public class Test {
static Set<Object> myServices = new HashSet<>();
public static <T> T get(Class<T> clazz) {
Optional<Object> result = myServices
.stream()
.filter(object -> object.getClass().equals(clazz) || clazz.isAssignableFrom(object.getClass()))
.findAny();
return result.isPresent() ? clazz.cast(result.get()) : null;
}
public static void main(String[] args) {
String myString = "this is a string";
Integer myInteger = 42069;
myServices.add(myString);
myServices.add(myInteger);
CharSequence myCharSequenceAgain = get(CharSequence.class);
Integer myIntegerAgain = get(Integer.class);
Double thisIsNull = get(Double.class);
System.out.println("CharSequence: " + myCharSequenceAgain);
System.out.println("Integer: " + myIntegerAgain);
System.out.println("Double: " + thisIsNull);
}
}
This returns:
CharSequence: this is a string
Integer: 42069
Double: null
So yeah it also works for superclasses etc
e.g. check it out, I stored a String and got it via get(CharSequence.class)
but how are you going to store all your instances in the set @sterile token ?
Yes
And how i will get a void method?
a void method?
I thought you wanted to store objects
there are no "void" objects
every object is at least of type Object
No no forget
I was asking if it was possible to do:
Service.get(Class.class).methodName()
But its possible
Am I able to implement support for net.md_5.bungee.api.ChatColor myself, inside of the Team interface? and if yes how would I do it
my whole code was made so you do NOT have to use reflection
it gives you at compile time the guarantee that your object will be of type clazz
yeah of course lol
How do I get the item that is getting moved to the inventory with a hotbar swap?
didn't you check the code? if your class is not in the set, it returns null, what else should it return?
Heee?
check the event's getClickedSlot, and getCurrentItem
?
explain
yeah, so?
trying to cancel hotswap of a certain item
For some reason its returning null when calling the methods
but I cant seem to find it
and what is not working with what mfnalex said
they both return air
because your set doesn't contain an instanceof the class you were trying to get
I dont understand what you refer to?
if the clicked item slot in the inventory is empty, it returns Material.AIR yes
Why it doesnt contain if have registered the class
idk, maybe you created more than one Service Class, or whatever
I can't tel you if you don't show the code you tried it with
I sent it
I sent you a fully working example code in one file and as you can see, it works perfectly fine
yes but I am definitely hot swapping an item so one of the many methods should have the item I am looking for
erm why do you return this
Service service = new Service().register(ServiceTest.class)? Why?
if not i cannot register multiple services at the same time
Like i have to do a new line per new register method
I will take that out
you should really learn how to use generics
public static <T> T register(T object) {
myServices.add(object);
return object;
}
Now you can do
and then event.setCancelled(true);
MyObject myObject = Test.register(new MyObject());
if the currentItem.getType is correct
Why neww?
That its want to skip using
public class Test {
private static Set<Object> myServices = new HashSet<>();
public static <T> T register(T object) {
myServices.add(object);
return object;
}
public static <T> T get(Class<T> clazz) {
Optional<Object> result = myServices
.stream()
.filter(object -> object.getClass().equals(clazz) || clazz.isAssignableFrom(object.getClass()))
.findAny();
return result.isPresent() ? clazz.cast(result.get()) : null;
}
public static void main(String[] args) {
String myString = register("this is a string");
Integer myInteger = register(42069);
CharSequence myCharSequenceAgain = get(CharSequence.class);
Integer myIntegerAgain = get(Integer.class);
Double thisIsNull = get(Double.class);
System.out.println("CharSequence: " + myCharSequenceAgain);
System.out.println("Integer: " + myIntegerAgain);
System.out.println("Double: " + thisIsNull);
}
}
Works 10000% fine @sterile token
Btww
nice int
because in my example, there is no myObject yet
and it does work fine
@charred echo but I know where the object is its on the playerInventory in a certain slot
The problem is that i want to register the class name and then in the service class its the responsable for creating the object isntance if it doesnt exists
only the event.getSlot() returns the destination slot
not the startSlot where the item came from
and what exactly is the problem?
Its returning null pointer exception
No it doesn't. It works fine. If it doesn't work, you did something wrong. This will work:```java
Jesus jesus = Test.get(Jesus.class);
if(jesus == null) jesus = Test.register(new Jesus());
im pretty sure
show the full error and then show the code from the line mentioned in the error
I think
ok
no that cant be right actually
@quaint bough you can just do InventoryClickEvent#isShiftClick
Verano you have no idea what you are doing
you have added an object of instance Class into your set
then you try to get the instance of an object of the class SErviceTest
you never added any ServiceTest object
yeah but I need the item that is getting swapped
not to check if it is getting swapped
I dont want to save the object i want i want to save the class instance with it methods
thats just the event item
you do service.register(ServiceTest.class)
but it isnt
ServiceTest.class is an object instanceof Class<?>
what do you mean by swapped
hover over item and press 1
or hover over slot andp ress one
what you obviously want to do is to register a NEW ServiceTest, and not ServiceTest.class
ah
@sterile token
then u do
I want to skip keyword new
Thats why i want this system
To skip doing new Class() and then getting its intance
.newInstance();
this can never work
Oh i will try
what if your class requires constructor params?
wouldent recommend it tho