二、探索Java的反射机制

通过java的反射来获取对象方法和设置对象的属性值:

package com.reflect;

public class Car {
    private String brand;

    private String color;

    private int maxSpeed;

    //1、默认构造函数
    public Car(){
        System.out.println("init car!");
    }

    //2、带参构造函数
    public Car(String brand, String color, int maxSpeed){
        this.brand = brand;
        this.color = color;
        this.maxSpeed = maxSpeed;
    }

    //3、未带参的方法
    public void introduce(){
        System.out.println("brand:"+brand+";color:"+color+";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 int getMaxSpeed() {
        return maxSpeed;
    }

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

反射机制测试类:

package com.reflect;

import java.lang.reflect.Constructor;
import java.lang.reflect.Method;


public class CarTest {
    /*
     * Constructor:获取所有构造函数的反射类
     * Method:获取所有类方法的反射类
     * */  
    public static Car initDefaultConst() throws Throwable
    {
        //1.通过类装载器获取Car类对象
        ClassLoader loader = Thread.currentThread().getContextClassLoader();
        Class clazz = loader.loadClass("com.reflect.Car");

        //2.获取类的默认构造器对象并实例化Car
        Constructor cons = clazz.getDeclaredConstructor((Class[])null);
        Car car = (Car)cons.newInstance();

        //3.通过反射方法设置属性
        Method setBrand = clazz.getMethod("setBrand", String.class);
        setBrand.invoke(car, "奔驰");
        Method setColor = clazz.getMethod("setColor", String.class);
        setColor.invoke(car, "粉红");
        Method setMaxSpeed = clazz.getMethod("setMaxSpeed", int.class);
        setMaxSpeed.invoke(car, 200);
        return car;
    }

    public static Car initByParamConst() throws Throwable {
        //1.通过类装载器获取Car类对象
        ClassLoader loader = Thread.currentThread().getContextClassLoader();
        Class clazz = loader.loadClass("com.reflect.Car");

        //2.获取类的带有参数的构造器对象
        Constructor cons = clazz.getDeclaredConstructor(new Class[]{String.class, String.class, int.class});

        //3.使参数的构造器对象实例化Car
        Car car = (Car)cons.newInstance(new Object[]{"宝马","骚红",180});
        return car;
    }

    public static void main(String[] args) throws Throwable {
        Car car1 = initDefaultConst();
        Car car2 = initByParamConst();
        car1.introduce();
        car2.introduce();
    }
}

显示结果:

init car!
brand:奔驰;color:粉红;maxSpeed:200
brand:宝马;color:骚红;maxSpeed:180

注:该代码为本人学习过程中的实验代码,谈不上原创,如有侵权请指出第一时间改正

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值