How to check if an offline player has permission?

Current code:
UserStorageService userStorage = Sponge.getServiceManager().provide(UserStorageService.class).get();
User user = userStorage.get(;
if (user.hasPermission(“test.permission”)) {

The problem is that the code is generating a NPE on user.hasPermission(…)

You need to do a userStorage.get( check before you do userStorage.get( This will ensure you don’t receive an NPE. If the user is not present then do not process it.

But doesn’t that require the player to be online – User#isPresent

isPresent is from the Optional class, which is used in place of possibly returning null. There’s an explanation of it on the docs, I would link it but I am not at my PC right now.

Found the link if you hadn’t found it already:

Thanks for the information, I did in fact implement that into the code…
But I ended up fixing my problem another way, as I was looking at the wrong code.
I cannot really explain it here, as it has nothing to do with this thread, but my issue is solved.

1 Like

If you call get on a nonexistent value, it will throw a NoSuchElementException. Working with Optionals, you never get null, unless you specifically call orElse(null).

1 Like