Search code examples
javareflectionnestedprivateinvoke

How to invoke method using reflection


Collections class has nested class private static class EmptyList<E> which has get(int index) method and does not have default constructor. How can I invoke get(int index) method?


Solution

  • You can create an instance of java.util.Collections$EmptyList and call its get(int) by using the code below. The code is fully tested and throws an IndexOutOfBoundsException as requested.

    import java.lang.reflect.Constructor;
    import java.util.List;
    
    public class Test {
    
        public static void main(String[] args) throws ReflectiveOperationException {
            Class<?> clazz = Class.forName("java.util.Collections$EmptyList");
            Constructor<?> constructor = clazz.getDeclaredConstructor();
            constructor.setAccessible(true);
            List<?> emptyList = (List<?>) constructor.newInstance();
    
            emptyList.get(0);
        }
    }
    

    Just because I am curious, could you probably provided more information on why you would want to do something like this?