dimanche 28 mars 2021

Java store reflected Method statically in class: Safe?

Is something like the following 'safe' in Java, and why?

public final class Utility {

    private Utility() {}

    private static Method sFooMethod = null;

    public static void callFoo(SomeThing thing) {
        try {
            if(sFooMethod == null)
                sFooMethod = SomeThing.class.getMethod("foo");
            sFooMethod.invoke(thing);
        } catch(Exception e) {}  // Just for simplicity here
    }

}

My rationale would be that even if another thread writes to sFooMethod in the background and the current thread sees it suddenly somewhere during execution of callFoo(), it would still just result in the same old reflective invoke of thing.foo()?

Extra question: In what ways does the following approach differ (positive/negative) from the above? Would it be preferred?

public final class Utility {

    private Utility() {}

    private static final Method sFooMethod;
    static {
        try {
            sFooMethod = SomeThing.class.getMethod("foo");
        } catch(Exception e) {}
    }

    public static void callFoo(SomeThing thing) {
        try {
            if(sFooMethod != null)
                sFooMethod.invoke(thing);
        } catch(Exception e) {}
    }

}




Aucun commentaire:

Enregistrer un commentaire