Gets the underlying collection wrapped by Collections.unmodifiableCollection(...) - Java java.util

Java examples for java.util:Collection Operation

Description

Gets the underlying collection wrapped by Collections.unmodifiableCollection(...)

Demo Code


import java.lang.reflect.Field;
import java.util.Collection;

public class Main{
    public static void main(String[] argv){
        Object collection = "java2s.com";
        System.out.println(getUnmodifiableCollection(collection));
    }/*from w w w.j  ava 2  s .c  o  m*/
    /**
     * Gets the underlying collection wrapped by Collections.unmodifiableCollection(...)
     * 
     * @param collection
     * @return
     */
    public static Collection<?> getUnmodifiableCollection(Object collection) {
        // Precondition checking
        //
        if (collection == null) {
            return null;
        }

        // Search the underlying field (named 'c')
        //
        Field field = IntrospectionHelper.getRecursiveDeclaredField(
                collection.getClass(), "c");
        if (field == null) {
            throw new RuntimeException(
                    "Unable to find the underlying collection of unmodifiable collection !");
        }

        try {
            field.setAccessible(true);
            return (Collection<?>) field.get(collection);
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage(), e);
        }
    }
}

Related Tutorials