vendredi 10 septembre 2021

Java 11 reflection

I need a general means to determine if reflective access is allowed to an object member. In Java 8, if the member is public and the class is public, then reflective access is allowed. In Java 11, this is no longer true. So how can I determine if reflective access is allowed to an object member in Java 11? Here is some sample code illustrating the problem:

import java.lang.reflect.*;
import javax.net.SocketFactory;
import javax.net.ssl.SSLSocketFactory;

public class Refl {
    public static void main(String[] args) throws Exception {
        //System.out.println(sun.security.ssl.SSLSocketFactoryImpl.class); // doesn't work
        SocketFactory sf = SSLSocketFactory.getDefault();
        SSLSocketFactory.class.getMethod("getDefaultCipherSuites").invoke(sf);
        Class cls = sf.getClass();
        System.out.println(cls);
        System.out.println(Modifier.isPublic(cls.getModifiers()));
        Method m = cls.getMethod("getDefaultCipherSuites");
        System.out.println(m);
        System.out.println(Modifier.isPublic(m.getModifiers()));
        m.invoke(sf);  // here is the issue
        System.out.println("done");
    }
}




Aucun commentaire:

Enregistrer un commentaire