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();
	}
	
}

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

重视基础,才能走的更远。
原文地址:https://www.cnblogs.com/xzlf/p/12681512.html