dimanche 18 février 2018

How to use reflection to make static nested class visible

I've run into a situation where I have to call two private methods in the superclass, so I thought reflection would solve my issues.

        Method applyCacheConcurrencyStrategy = clazz.getDeclaredMethod("applyCacheConcurrencyStrategy", CacheHolder.class);
        Method applyCollectionCacheConcurrencyStrategy = clazz.getDeclaredMethod("applyCollectionCacheConcurrencyStrategy", CacheHolder.class);

The problem is that the class Cacheholder is a static nested class of the superclass, so firstly I just copied that class to my subclass. That only got rid of the compiler error. The problem that occurs now instead that I get a NoSuchMethodException, because the CacheHolder class in the superclass is not visible and is not recognized outside of the class.

I need this static inner class to be visible in order to do the following:

Field field;
        try {
        field = Configuration.class.getDeclaredField("caches");
        field.setAccessible(true);
        Object cachesRefl = field.get(this);
        List<CacheHolder> caches = (List<CacheHolder>) cachesRefl; 
        //CacheHolder is not visible
        Class<?> clazz = Class.forName("org.hibernate.cfg.Configuration");
        Method applyCacheConcurrencyStrategy = clazz.getDeclaredMethod("applyCacheConcurrencyStrategy", CacheHolder.class);
        Method applyCollectionCacheConcurrencyStrategy = clazz.getDeclaredMethod("applyCollectionCacheConcurrencyStrategy", CacheHolder.class);
        applyCacheConcurrencyStrategy.setAccessible(true);
        applyCollectionCacheConcurrencyStrategy.setAccessible(true);
        for (CacheHolder holder : caches) {
            if (holder.isClass) {
                applyCacheConcurrencyStrategy.invoke(this,holder);
            } else {
                applyCollectionCacheConcurrencyStrategy.invoke(this,holder);
            }
        }
        caches.clear();
        }catch (NoSuchFieldException | SecurityException | NoSuchMethodException | ClassNotFoundException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
            e.printStackTrace();
        }

Is there something I can do in order to make the methodcalls with the CacheHolder.class as parameter?





Aucun commentaire:

Enregistrer un commentaire