所有分类
  • 所有分类
  • 未分类

Java反射–反射的应用

简介

本文用示例介绍Java反射的应用。

调用类的方法

package org.example.a;

import java.lang.reflect.Method;

class Human {
    private String name;
    private Integer age;

    public Human() {
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }


    public void sayCategory() {
        System.out.println("HUMAN");
    }

    public String sayHello(String name, Integer age) {
        return "名字:" + name + " " + "年龄:" + age;
    }
}


public class Demo {
    public static void main(String[] args) {
        Class<?> c = null;
        try {
            c = Class.forName("org.example.a.Human");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }

        try {
            Method method = c.getMethod("sayHello", String.class, Integer.class);
            System.out.println(method.invoke(c.newInstance(), "Tony", 20));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

执行结果

名字:Tony 年龄:20

修改属性

package com.example.a;

import java.lang.reflect.Field;


public class Demo {
    public static void main(String[] args) {
        User user = new User();

        try {
            Class<? extends User> aClass = user.getClass();
            Field nameField = aClass.getDeclaredField("name");
            nameField.setAccessible(true);   //将name属性设置成可被外部访问
            nameField.set(user, "Tony");     //设置name属性内容
            
            System.out.println(user.getName());
            // 也可以这么写:
            // System.out.println(nameField.get(user));

            nameField.setAccessible(false);  //将name属性设置成不可被外部访问
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

class User {
    private String name;
    private Integer age;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public void sayCategory() {
        System.out.println("HUMAN");
    }

    public String sayHello(String name, Integer age) {
        return "名字:" + name + " " + "年龄:" + age;
    }
}

执行结果

Tony

获取父类属性

反射只能操作本类的private属性,无法操作父类的private属性。如果想操作父类的,需要通过getSuperClass获得父类,然后再操作。

package com.example.a;

import java.lang.reflect.Field;

public class Demo {
    public static void main(String[] args) {
        User user = new User();
        user.setId(3L);
        user.setUserName("Tony");
        user.setCurrent(4);
        user.setPageSize(20);

        System.out.println("------ Class的getDeclaredFields ------");
        Class<? extends User> aClass = user.getClass();
        Field[] declaredFields = aClass.getDeclaredFields();
        for (Field declaredField : declaredFields) {
            System.out.println(declaredField.getName());
        }

        System.out.println("------ Class的getSuperClass的getDeclaredFields ------");

        Class<?> superclass = aClass.getSuperclass();
        Field[] superFields = superclass.getDeclaredFields();
        for (Field declaredField : superFields) {
            String name = declaredField.getName();
            System.out.println(name);
        }
    }
}

class PageRequest {
    private Integer current = 0;

    private Integer pageSize = 10;

    public Integer getCurrent() {
        return current;
    }

    public void setCurrent(Integer current) {
        this.current = current;
    }

    public Integer getPageSize() {
        return pageSize;
    }

    public void setPageSize(Integer pageSize) {
        this.pageSize = pageSize;
    }
}

class User extends PageRequest{
    private Long id;

    private String userName;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }
}

结果

------ Class的getDeclaredFields ------
id
userName
------ Class的getSuperClass的getDeclaredFields ------
current
pageSize

操作数组

例1:取得数组信息并修改数组内容

package org.example.a;

import java.lang.reflect.Array;

public class Demo {
    public static void main(String[] args) {
        int temp[] = {1, 2, 3};
        Class<?> c = temp.getClass().getComponentType();
        System.out.println("类型:" + c.getName());
        System.out.println("长度:" + Array.getLength(temp));
        System.out.println("第一个内容:" + Array.get(temp, 0));
        Array.set(temp, 0, 6);
        System.out.println("第一个内容:" + Array.get(temp, 0));
    }
}

执行结果

类型:int
长度:3
第一个内容:1
第一个内容:6

例2:修改数组的大小

package org.example.a;

import java.lang.reflect.Array;


public class Demo {
    public static void main(String[] args) {
        int temp[] = {1, 2, 3};
        int newTemp[] = (int[]) arrayInc(temp, 5);
        print(newTemp);
        System.out.println("---------------------------");
        String str[] = {"abc", "def", "gh"};
        String newStr[] = (String[]) arrayInc(str, 8);
        print(newStr);
    }

    public static Object arrayInc(Object obj, int len) {
        Class<?> c = obj.getClass();
        Class<?> arr = c.getComponentType();
        Object newO = Array.newInstance(arr, len);
        int co = Array.getLength(obj);
        System.arraycopy(obj, 0, newO, 0, co);
        return newO;
    }

    public static void print(Object obj) {
        Class<?> c = obj.getClass();
        if (!c.isArray()) {
            return;
        }
        Class<?> arr = c.getComponentType();
        System.out.println(arr.getName() + "数组长度是:" + Array.getLength(obj));
        for (int i = 0; i < Array.getLength(obj); i++) {
            System.out.println(Array.get(obj, i) + "、");
        }
    }
}

执行结果

int数组长度是:5
1、
2、
3、
0、
0、
---------------------------
java.lang.String数组长度是:8
abc、
def、
gh、
null、
null、
null、
null、
null、
0

评论0

请先

显示验证码
没有账号?注册  忘记密码?

社交账号快速登录