jeudi 29 juillet 2021

How to filter the reflection for a field, after accessing it (with reflection)?

I was trying to make a system, where a class has a super-secret field (intero) and only the class itself and ANOTHER CLASS can access it. Then, there is a third class which i want to not have the permission to access that field.

The problem is - in java, you can use Reflections.registerFieldsToFilter() only before a field is accessed. If someone accesses a field you want to restrict, before it is restricted, then it can't be restricted anymore (or it can?). This is the code i tried:

public static void main(String[] args) {

    CanAccess.getInteroField();

    try {
        Reflection.registerFieldsToFilter(Main.class, "intero");
    } catch (Exception e) {
        e.printStackTrace();
    }

    CannotAccess.getInteroField();
}

and this is the content of getInteroField() in those 2 classes:

public static void getInteroField() {
    try {
        Field interoField = Main.class.getDeclaredField("intero");
        System.out.println("CannotAccess accessed!");
    } catch (Exception e) {
        System.out.println("CannotAccess failed to access!");
    }
}

So, the output i expected was this:

CanAccess accessed!
CannotAccess failed to access!

BUT the result i get is this:

CanAccess accessed!
CannotAccess accessed!

And if i comment the CanAccess.getInteroField(), the CannotAccess really cannot access.

So, all i need is a way to filter a field after it has been accessed.





Aucun commentaire:

Enregistrer un commentaire