如何使用反射调用方法
How to invoke method using reflection
Collections
class 嵌套了 class private static class EmptyList<E>
,它有 get(int index)
方法但没有默认构造函数。如何调用 get(int index)
方法?
您可以创建一个 java.util.Collections$EmptyList
的实例并使用下面的代码调用它的 get(int)
。代码已经过全面测试并按要求抛出 IndexOutOfBoundsException
。
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);
}
}
只是因为我很好奇,您能否提供更多信息来说明您为什么要这样做?
Collections
class 嵌套了 class private static class EmptyList<E>
,它有 get(int index)
方法但没有默认构造函数。如何调用 get(int index)
方法?
您可以创建一个 java.util.Collections$EmptyList
的实例并使用下面的代码调用它的 get(int)
。代码已经过全面测试并按要求抛出 IndexOutOfBoundsException
。
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);
}
}
只是因为我很好奇,您能否提供更多信息来说明您为什么要这样做?