java 反射之越过泛型检查

反射之前,我们知道在集合类中一旦指定了泛型的类型,则只能在该集合中用该类型。但是我们可以利用反射机制来越过泛型检查。比如说利用反射机制获取ArrayList中的add()方法,再调用add方法时,就会越过泛型检查,只是由于泛型检查是在编译时期进行的,也就是说编译后的add()方法其实和没有指定泛型的add()方法是一致的,都是不能进行泛型检查的。所以通过反射获取ArrayList的Class文件对象中的add()方法,在调用该add()方法时是不用泛型检查的。如下所示:

测试主类

package cn.edu.tju.versace;

import java.lang.reflect.Method;
import java.util.ArrayList;

import cn.edu.tju.reflect.Student;

/**
 * 反射越过泛型检查
 * @author feige
 */
public class ReflectDemo {

    public static void main(String[] args) throws Exception {
     ArrayList<Integer> arrayList=new ArrayList<Integer>();//指定泛型为Integer
     Class c=arrayList.getClass();//获取Class文件对象
     Method addMethod=c.getDeclaredMethod("add",Object.class);//获取Class文件对象中的add()方法
     Student  s=new Student("arui",25);
     addMethod.invoke(arrayList, "afei");//越过泛型检查,添加String类型
     addMethod.invoke(arrayList, s);//越过泛型检查,添加Student类型
     System.out.println(arrayList);//结果为:[afei, Student [name=arui, age=25]]
    }

}
Student类:

package cn.edu.tju.reflect;

public class Student {
 private String name;
 public int age;
 
public Student(String name, int age) {
    super();
    this.name = name;
    this.age = age;
}

private Student() {
    super();
}

private void showName(String name) {
    this.name=name;
    System.out.println("name is:"+name);
}

public int showAge() {
    return age;
}

@Override
public String toString() {
    return "Student [name=" + name + ", age=" + age + "]";
}

}

  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值