mardi 30 juin 2015

Even when a class is final and its constructor is private, it can still be instantiated by reflection, as the example below shows. If Oracle really intended java.lang.Void not to have any instances, then why didn't they make its constructor throw an exception the way java.lang.Class.<init> does?

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.concurrent.ExecutionException;

public class VoidWhereProhibited {

    public static void main(String[] args) throws IllegalAccessException, InvocationTargetException,
            InstantiationException, NoSuchMethodException, ExecutionException, InterruptedException {
        Method privateGetDeclaredConstructors = Class.class.getDeclaredMethod("privateGetDeclaredConstructors",
                boolean.class);
        privateGetDeclaredConstructors.setAccessible(true);
        Constructor<Void> newVoid = ((Constructor<Void>[])privateGetDeclaredConstructors.invoke(Void.class, false))[0];
        newVoid.setAccessible(true);
        final Void v = newVoid.newInstance();
        System.out.println(v);
    }
}





Aucun commentaire:

Enregistrer un commentaire