Java注解与反射(八)

这是我参与11月更文挑战的第25天,活动详情查看:2021最后一次更文挑战

2.10 性能对比分析

 package refection;
 ​
 import java.lang.reflect.InvocationTargetException;
 import java.lang.reflect.Method;
 ​
 // 性能对比测试
 @SuppressWarnings("all")
 public class Test09 {
     // 用两种方式调用一个方法10亿次,看看所需要的时间
 ​
     // 普通的方式
     public static void test01(){
         User user = new User();
         long startTime = System.currentTimeMillis();
 ​
         for (int i = 0; i < 1000000000; i++) {
             user.getName();
         }
 ​
         long endTime = System.currentTimeMillis();
 ​
         System.out.println("普通方式运行10亿次所需要的时间为:" + (endTime - startTime) + "ms");
 ​
     }
 ​
 ​
     // 通过反射的方式
     public static void test02() throws ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException {
         Class c1 = Class.forName("refection.User");
 ​
         User user = (User)c1.newInstance();
         Method getName = c1.getDeclaredMethod("getName" );
 ​
         long startTime = System.currentTimeMillis();
 ​
         for (int i = 0; i < 1000000000; i++) {
             getName.invoke(user,null);
         }
 ​
         long endTime = System.currentTimeMillis();
 ​
         System.out.println("通过反射运行10亿次所需要的时间为:" + (endTime - startTime) + "ms");
     }
 ​
 ​
     // 关闭检测
     public static void test03() throws ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException {
         Class c1 = Class.forName("refection.User");
 ​
         User user = (User)c1.newInstance();
         Method getName = c1.getDeclaredMethod("getName" );
         getName.setAccessible(true);
 ​
         long startTime = System.currentTimeMillis();
 ​
         for (int i = 0; i < 1000000000; i++) {
             getName.invoke(user,null);
         }
 ​
         long endTime = System.currentTimeMillis();
 ​
         System.out.println("关闭检测运行10亿次所需要的时间为:" + (endTime - startTime) + "ms");
     }
 ​
     public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
         test01();
         test02();
         test03();
     }
 ​
     /**普通方式运行10亿次所需要的时间为:4ms
      通过反射运行10亿次所需要的时间为:2258ms
      关闭检测运行10亿次所需要的时间为:1151ms*/
     
 }
 ​
复制代码

2.11 获取泛型信息

使用较少

  • Java采用泛型擦除的机制来引入泛型,Java中的泛型仅仅是给编译器javac使用的,确保数据的安全性以及免去强制类型转换的问题,但是,一旦编译完成,所有和泛型有关的类型会全部擦除
  • 为了能够通过反射来操作这些类型,Java新加了Parameterized Type , GenericArray Type,TypeVariable和WildcardType 几种类型来代表不能被归一到Class类中的类型但是又和原始类型齐名的类型
  • Parameterized Type : 表示一种参数化类型,比如Collection,String是参数化类型
  • GenericArray Type:表示一种元素类型是参数化类型或者类型变量的数组类型
  • TypeVariable:是各种类型变量的公共父接口
  • WildcardType :代表一种通配符类型表达式

Guess you like

Origin juejin.im/post/7034688404826619941