dimanche 23 janvier 2022

Can I mark a field as inaccessible within a Java class (the defining class itself)?

In a JNI environment, I want my Java class to contain some private fields, which I want to explicitly mark as "off limits" for Java access, so only my native code can use them.

So basically I have

public class Example() {
   private int var;
   private int varInternalState;

   public native void nativeMethod(...);
   public void otherMethod() { ... }
}

nativeMethod() needs some internal state information per object, which I want to keep in varInternalState. (I know how to do this; it works). But I want to mark varInternalState as "off limits" for otherMethod(), because it makes absolutely no sense to access it from Java, and I want to get a compiler error - or at least warning - if my future self or someone unfamiliar with the code acidentially reads or writes it.

Declaring it private doesn't help, because this is about accesses from the class itself, not from other classes.

And because of some Reflection magic, I don't want to give a name like doNotEverTouchThis to the internal variable; I'd like to stay free in naming that thing.

I think there's no keyword in Java to do this as I can't explicitly mark fields as synthetic, so I guess Annotations might help - however, I know next to nothing about them, and I don't want to reinvent the wheel if possible.

So, is there a clever way to declare varInternalState, or an existing annotation library that lets me do something like @Inaccessible private int varInternalState, which makes the compiler spit an error whenever I try to read/write the field?





Aucun commentaire:

Enregistrer un commentaire