Java反射的用法

Class类

在Java中,每个class都有一个相应的Class对象。也就是说,当我们编写一个类,编译完成后,在生成的.class文件中,就会产生一个Class对象,用于表示这个类的类型信息。

反射

Java的反射主要就是使用class对象生成对应类的实例、调用类的方法等对操作。示例代码:

Car.java

public class Car {

    private String brand;

    private String color;

    private Integer maxSpeed;

    public Car() {
    }

    public Car(String brand, String color, Integer maxSpeed) {
        super();
        this.brand = brand;
        this.color = color;
        this.maxSpeed = maxSpeed;
    }

    public String getBrand() {
        return brand;
    }

    public void setBrand(String brand) {
        this.brand = brand;
    }

    public String getColor() {
        return color;
    }

    public void setColor(String color) {
        this.color = color;
    }

    public Integer getMaxSpeed() {
        return maxSpeed;
    }

    public void setMaxSpeed(Integer maxSpeed) {
        this.maxSpeed = maxSpeed;
    }

    @Override
    public String toString() {
        return "Car [brand=" + brand + ", color=" + color + ", maxSpeed="
                + maxSpeed + "]";
    }

    public void testPrivate() {
        System.out.println("call testPrivate()");
    }

}

ReflectTest.java

public class RelectTest {

    public static void main(String[] args) throws ClassNotFoundException,
            InstantiationException, IllegalAccessException, SecurityException,
            NoSuchFieldException, NoSuchMethodException,
            IllegalArgumentException, InvocationTargetException {
        // 创建class,方法1
        Class<?> clazz = Class.forName("com.Car");
        // 创建class,方法2,相对来说,方法1更适合从配置中读取包的限定名字符串,避免了方法2中需要导包的操作
        clazz = Car.class;
        // 创建对象
        Car car = (Car) clazz.newInstance();
        // 获取所有的属性
        Field[] fields = clazz.getDeclaredFields();
        System.out.print("All fields:");
        for (Field field : fields) {
            System.out.print(field.getName() + ",");
        }
        System.out.println();
        // 获取所有的public属性
        Field[] publicFilds = clazz.getFields();
        System.out.print("All public fields:");
        for (Field field : publicFilds) {
            System.out.print(field.getName() + ",");
        }
        System.out.println();
        // 获取继承或接口中的所有方法
        Method[] methods = clazz.getMethods();
        System.out.println("All methods:");
        for (Method method : methods) {
            System.out.println(method.getReturnType() + " " + method.getName()
                    + "(" + displayClass(method.getParameterTypes()) + ")");
        }
        System.out.println();
        // 获取本类中的public, protected, private方法,不包括继承的方法
        Method[] selfMethods = clazz.getDeclaredMethods();
        System.out.println("All self methods:");
        for (Method method : selfMethods) {
            System.out.println(method.getReturnType() + " " + method.getName()
                    + "(" + displayClass(method.getParameterTypes()) + ")");
        }
        System.out.println();
        // 获取构造函数
        Constructor[] constructors = clazz.getDeclaredConstructors();
        System.out.println("All Constructor:");
        for (Constructor constructor : constructors) {
            System.out.println(constructor.getName() + "("
                    + displayClass(constructor.getParameterTypes()) + ")");
        }
        System.out.println();

        // 获取指定的属性
        Field brandField = clazz.getDeclaredField("brand");
        // 通过属性为字段赋值
        brandField.setAccessible(true);// 由于brand属性为private,必须设置覆盖java对该字段的访问控制检查
        brandField.set(car, "奔驰");
        System.out.println(car);

        // 获取指定的方法
        Method colorSetMethod = clazz.getDeclaredMethod("setColor",
                String.class);
        colorSetMethod.invoke(car, "黑色");
        System.out.println(car);

        Method testPrivateMethod = clazz.getDeclaredMethod("testPrivate");
        testPrivateMethod.invoke(car, null);

    }

    public static String displayClass(Class[] s) {
        StringBuilder sb = new StringBuilder();
        for (Class c : s) {
            if (sb.length() > 0)
                sb.append(", ");
            sb.append(c.getName());
        }
        return sb.toString();
    }

}

转载于:https://www.cnblogs.com/acode/p/7421397.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值