Use Object from another class in Listener

Hello,

I've been coding plugins for a little while now. I've ran into an issue where I can't figure out how to use an object from another class in a listener. Yes, I've googled it. I've been told I need to use a constructor, but when I use one, it never works properly. To better explain my issue I'll give an example.

Lets say I create an ArrayList to store UUID's, and I want to get that array list from a Listener in my Listeners class. Usually I just make it a static variable to get it, but I know this is bad and I'm trying to remove that habit. If I create a class object variable I can use that ArrayList in a command, but I can't in a Listener, and I'm not totally sure why this is.

Any help would be appreciated, thank you!
 
Several things:

Using static keyword isn’t necessarily bad- for example, it’s ok to use static in utility methods and constants. However yes, making a method static just because “I need to access this in another class!” is static abuse and you shouldn’t do it.

If you want to, as an example, access your main class’s instance to use methods like getConfig or getLogger in another class, you have 2 options: use the singleton method, or what most people prefer, dependency injection. You can use similar methods for your list if you see fit.

You can search up “OOP Principals Java” and there will be several online topics and how to code the proper way, why static is bad in some cases, etc.

If you need any code samples or more info on how to make a singleton or do dependency injection, hit me up on Discord and I’ll explain in more detail tomorrow (if you contact me today). Currently on mobile :p
 
Several things:

Using static keyword isn’t necessarily bad- for example, it’s ok to use static in utility methods and constants. However yes, making a method static just because “I need to access this in another class!” is static abuse and you shouldn’t do it.

If you want to, as an example, access your main class’s instance to use methods like getConfig or getLogger in another class, you have 2 options: use the singleton method, or what most people prefer, dependency injection. You can use similar methods for your list if you see fit.

You can search up “OOP Principals Java” and there will be several online topics and how to code the proper way, why static is bad in some cases, etc.

If you need any code samples or more info on how to make a singleton or do dependency injection, hit me up on Discord and I’ll explain in more detail tomorrow (if you contact me today). Currently on mobile :p
I feel like if you need to access a method or object and that method or object is a constant variable then its perfectly fine to use static, a lot of you minecraft devs seem to overuse objects for some reason I don't know why, maybe its a dominance thing
 
Top