zoukankan      html  css  js  c++  java
  • Java 反射调用方法

    java中反射提供灵活性同时,给运行效率带来了一定影响。写个代码测试一下

    package com.xzlf.reflectTest;
    
    import java.lang.reflect.Method;
    
    import com.xzlf.bean.User;
    
    /**
     * 反射、反射跳过安全检查、普通方法调用性能比较
     * @author xzlf
     *
     */
    public class Demo04 {
    	// 普通方法调用
    	public static void test01() {
    		User u = new User();
    		long start = System.currentTimeMillis();
    		for (int i = 0; i < 1000000000L; i++) {
    			u.getName();
    		}
    		long end = System.currentTimeMillis();
    		System.out.println("普通方法调用,执行10亿次,耗时:" + (end - start) + "ms");
    	}
    	// 反射调用,不跳过安全检查
    	public static void test02() throws Exception {
    		User u = new User();
    		Class clz = u.getClass();
    		Method m = clz.getDeclaredMethod("getName", null);
    		
    		long start = System.currentTimeMillis();
    		for (int i = 0; i < 1000000000L; i++) {
    			m.invoke(u, null);
    		}
    		long end = System.currentTimeMillis();
    		System.out.println("反射动态方法调用,执行10亿次,耗时:" + (end - start) + "ms");
    	}
    	// 反射调用,跳过安全检查
    	public static void test03() throws Exception {
    		User u = new User();
    		Class clz = u.getClass();
    		Method m = clz.getDeclaredMethod("getName", null);
    		m.setAccessible(true);// 跳过安全检查
    		long start = System.currentTimeMillis();
    		for (int i = 0; i < 1000000000L; i++) {
    			m.invoke(u, null);
    		}
    		long end = System.currentTimeMillis();
    		System.out.println("反射动态方法调用,跳过安全检查,执行10亿次,耗时:" + (end - start) + "ms");
    	}
    	
    	public static void main(String[] args) throws Exception {
    		test01();
    		test02();
    		test03();
    	}
    	
    }
    
    

    运行测试:
    在这里插入图片描述

    重视基础,才能走的更远。
  • 相关阅读:
    PHP入门03 -- 数组与数据结构
    PHP入门02 -- 函数
    PHP入门01 -- 基本语法
    node文章
    Mongodb08
    Mongodb07
    ISO处理jq事件
    map
    Django自定义模板
    JS this指向
  • 原文地址:https://www.cnblogs.com/xzlf/p/12681512.html
Copyright © 2011-2022 走看看