Java 反射机制

获取类对象的三种方法

Class aClass1 = new Object().getClass();
Class aClass2 = Object.class;
Class aClass3 = Class.forName("java.lang.Object");

调用默认构造器

Class aClass = Class.forName("java.util.Random");
Object obj = aClass.newInstance();

获取类信息

获取类中声明的私有、受保护、公有的属性、构造器和方法,不包含超类的:

Field[] declaredFields = aClass.getDeclaredFields();
Constructor[] declaredConstructors = aClass.getDeclaredConstructors();
Method[] declaredMethods = aClass.getDeclaredMethods();

获取类和超类中公有的属性、构造器和方法:

Field[] fields = aClass.getFields();
Constructor[] constructors = aClass.getConstructors();
Method[] methods = aClass.getMethods();

分析修饰符:

Class randomClass = Class.forName("java.util.Random");
Field seed = randomClass.getDeclaredField("seed");
Modifier.isPrivate(seed.getModifiers());
Modifier.isFinal(seed.getModifiers());

操作对象的属性

Integer obj = new Integer("100");
Class aClass = Class.forName("java.lang.Integer");
Field valueField = aClass.getDeclaredField("value");
valueField.setAccessible(true);
// 查看属性值
int intValue = (int) valueField.get(obj); // 100
// 设置属性值
valueField.set(obj, 200);
intValue = valueField.getInt(obj); // 200

调用方法

调用对象方法:

Class aClass = Class.forName("java.util.Random");
Object obj = aClass.newInstance();

Method nextIntMethod = aClass.getMethod("nextInt", int.class);
Integer invoke = (Integer) nextIntMethod.invoke(obj, 10); // 第一个参数是对象实例

调用静态方法:

Class aClass = Class.forName("java.lang.Math");
Method maxMethod = aClass.getDeclaredMethod("max", int.class, int.class);

Integer invoke = (Integer) maxMethod.invoke(null, 100, 200); // 调用静态方法,将对象实例参数设置为 null

数组

按原数组的 2 倍进行扩容:

private static Object resize(Object array) {
    Class<?> aClass = array.getClass();
    if (!aClass.isArray()) {
        return array;
    }
    int length = Array.getLength(array);
    int newLength = 2 * length;
    Object newArray = Array.newInstance(aClass.getComponentType(), newLength);
    System.arraycopy(array, 0, newArray, 0, length);
    return newArray;
}
posted @ 2022-07-10 19:21  廖子博  阅读(25)  评论(0编辑  收藏  举报