性能问题:
* 反射机制性能问题:反射使代码灵活,提高了开发效率,也带来了性能问题,运行效率。
* 反射的对象在使用是会有安全检查,我们可以通过setAccessible方法来
* 启用和禁用访问安全检查的开关,true:取消访问检查,false:实施访问
* 检查。禁止安全检查,可以提高反射的运行速度。
field.setAccessible(true);//不需要安全检查,可以直接访问
反射操作泛型:
* 反射操作泛型
* Java采用泛型擦除的机制来引入泛型,泛型只是给编译器用的,确保数据的
* 安全性和免去强制类型转换的麻烦。但是,一旦编译完成,所有的和泛型有
* 关的类型全部擦除,所以反射是不能直接读取到泛型的。
* 为了反射也能操作泛型,新增了:
* parameterizedType:表示一种参数化的类型:collection<String>
* genericArrayType:表示一种元素类型是参数化类型或者类型变量的数组类型
* typeVariable:各种类型变量的公共父接口
* wildrardType:代表一种通配符类型表达式
public class Test3 {
public void test1(Map<String,Student> map, List<Student> list){
System.out.println("Test3.test1()");
}
public Map<Integer,Student> test2(){
System.out.println("Test3.test2()");
return null;
}
public static void main(String[] args) {
try {
//获取指定方法的参数泛型信息
Method m = Test3.class.getMethod("test1",Map.class,List.class);
Type[] t = m.getGenericParameterTypes();//获得带泛型参数类型,Type是那4种接口的父类
for(Type temp:t){
System.out.println("#"+temp);
if(temp instanceof ParameterizedType){//判断是不是参数化类型
//是就强制转参数化类型,getActualTypeArguments获得真正的参数类型
Type[] genericTypes = ((ParameterizedType) temp).getActualTypeArguments();
for(Type genericType:genericTypes){
System.out.println("泛型类型"+genericType);
}
}
}
//获得指定方法返回值泛型信息
Method m2 = Test3.class.getMethod("test2",null);
Type t2 = m2.getGenericReturnType();//返回值类型
if(t2 instanceof ParameterizedType){//判断是不是参数化类型
//是就强制转参数化类型,getActualTypeArguments获得真正的参数类型
Type[] genericTypes = ((ParameterizedType) t2).getActualTypeArguments();
for(Type genericType:genericTypes){
System.out.println("泛型类型"+genericType);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
执行:
#java.util.Map<java.lang.String, cn.oyh.annotation.Student>
泛型类型class java.lang.String
泛型类型class cn.oyh.annotation.Student
#java.util.List<cn.oyh.annotation.Student>
泛型类型class cn.oyh.annotation.Student
泛型类型class java.lang.Integer
泛型类型class cn.oyh.annotation.Student
反射操作注解:
public class Demo {
public static void main(String[] args) {
try {
//获取Student类所有信息
Class c = Class.forName("cn.oyh.annotation.Student");
//获得类的所有注解
Annotation[] annotation=c.getAnnotations();
for (Annotation a:annotation){
System.out.println(a);
}
//获得类指定注解信息
StudentTable table = (StudentTable) c.getAnnotation(StudentTable.class);
System.out.println(table.value());
//获得类的属性的注解
Field f = c.getDeclaredField("age");
StudentField field = f.getAnnotation(StudentField.class);
System.out.println(field.columnName()+"--"+field.type()+"--"+field.length());
} catch (Exception e) {
e.printStackTrace();
}
}
}
以上是对自定义注解进行操作,执行:
@cn.oyh.annotation.StudentTable(value=tb_student)
tb_student
age--int--3

本文探讨了Java反射机制带来的性能影响,并详细分析了如何使用反射操作泛型和注解。通过示例代码展示了反射在处理泛型类型时的效率问题,以及对自定义注解进行读取和应用的方法。
748

被折叠的 条评论
为什么被折叠?



