samedi 8 janvier 2022

Question about how to use the java reflection API

The goal is to modify the value by accessing the private instance in the code below.

public class mySingleton5 {
//Double check lock


//Volatile stores Java variables in Main Memory and reads them from Main Memory, not r/w to CPU cache.
private volatile mySingleton5 instance;

private mySingleton5(){}
public mySingleton5 getInstance(){
    if(instance == null){ //Single tone class, locked transfer.
        synchronized (mySingleton5.class){
            if(instance == null){ //When you create an object,
                instance = new mySingleton5();
            }
        }
    }
    return instance;
}

}

In order to access the instrument, I wrote the reflection API code as below. In order to change the field value, you have to create the class object written above, but it is private, so you cannot create the object and hand it over to the first element of the set function.

    Class<mySingleton5> msclass = mySingleton5.class;
    System.out.println("Class name: "+msclass.getName());
    Class clazz2 = Class.forName("mySingleton5");
    Field fld = clazz2.getDeclaredField("instance");
    fld.setAccessible(true);
    fld.set("???", "123"); //error
    System.out.println(fld.get(msclass));

Is there any way to access fields of a private class?

Aucun commentaire:

Enregistrer un commentaire