Paper icon indicating copy to clipboard operation
Paper copied to clipboard

Add support for private constructors in plugin main classes

Open Wiicart opened this issue 6 months ago • 8 comments

Adds support for private constructors in plugin main classes, using Constructor#setAccessible(boolean), allowing for better encapsulation.

Wiicart avatar Jun 10 '25 21:06 Wiicart

What is the benefit of allowing private constructors to be used?

Warriorrrr avatar Jun 11 '25 18:06 Warriorrrr

What is the benefit of allowing private constructors to be used?

The only benefit I can think of would be that it makes sure people, who use your plugin's API, which may come with internal classes exposed, cannot accidentally create an instance of your plugin's main class.

A potential solution to this is making the constructor package-private and creating the plugin instance with a plugin bootstrapper, but I can see how this might be non-ideal.

Strokkur424 avatar Jun 11 '25 19:06 Strokkur424

Doesn't creating a new javaplugin instance result in an exception already? I thought it did...

mbax avatar Jun 11 '25 20:06 mbax

What Strokkur said is pretty much what I was thinking. I’ll admit I wasn’t aware of an Exception when making new JavaPlugin instances, but even so, I don’t think it would hurt to prevent it at compile time.

Wiicart avatar Jun 11 '25 21:06 Wiicart

I think its probably fine to allow non-public constructors*.

Machine-Maker avatar Jun 11 '25 23:06 Machine-Maker

However, can you also please update ProviderUtil#loadClass? This way this applies to paper plugins too.

Owen1212055 avatar Jun 21 '25 05:06 Owen1212055

Isn't setAccessible unofficially deprecated? I think the replacement is called trySetAccessible

NonSwag avatar Jun 21 '25 08:06 NonSwag

However, can you also please update ProviderUtil#loadClass? This way this applies to paper plugins too.

Done

Isn't setAccessible unofficially deprecated? I think the replacement is called trySetAccessible

I looked at trySetAccessible, the only difference is that instead of throwing an InaccessibleObjectException, it returns false, but it can still throw a SecurityException.

Wiicart avatar Jun 21 '25 17:06 Wiicart