Java 反射创建对象

public class Toy {
    private int i;

    public Toy() {}
    public Toy(int i) { this.i = i; }

    public int getI() {
        return i;
    }

    public int getValue(int val) {
        return val;
    }
}

public class ReflectTest {
    public static void main(String[] args) throws Exception {
        //反射获取实例
        //getConstructor参数为某一个构造器的参数类型
        //newInstance 参数为该构造器的参数
        Class<Toy> toyClass = Toy.class;
        Constructor<Toy> constructor = toyClass.getConstructor(int.class);
        Toy toy = constructor.newInstance(1);

        //通过反射调用对象的方法
        //第一个参数为方法名
        //第二个参数为参数类型,如果方法有多个参数,这里也需要对应的参数个数
        Method method = toyClass.getMethod("getValue", int.class);
        System.out.println(method.invoke(toy, 10));

        //通过反射获取域
        //参数为域的名字
        Field field = toyClass.getDeclaredField("i");
        //如果为private类型,通过下面的方法设置允许访问
        field.setAccessible(true);
        //设置toy对象的 i 值为 12, 由于i为private,
        //需要使用上面的方法,否则抛出异常
        field.set(toy, 12);
        System.out.println(toy.getI());
    }
}
  • Class<Toy> toyClass = Toy.class; 获取Toyclass,当然也可以使用Class.forName获得,不过它获得需要处理一下。
  • toyClass.getConstructor(int.class);获取Toy的带有一个int型参数的构造器。
  • Toy toy = constructor.newInstance(1); 使用上面获取的构造器实例化,参数为该构造器需要的参数。
  • Method method = toyClass.getMethod("getValue", int.class);获得Toy的参数为一个int型值的getValue方法。
  • method.invoke(toy, 10) 调用Toy实例toygetValue方法,参数为10,必须和上面获取到的方法参数类型对应。
  • Field field = toyClass.getDeclaredField("i"); 获取Toy类的i域。
  • field.setAccessible(true);如果该域为private,通过该方法设置能够被访问,不然会抛出异常。
  • field.set(toy, 12);设置Toy实例toyi域值为12
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值