---
title: "8.53 在反射里使用接口"
author: "bingooh"
date: "2013-08-16T14:48:29Z"
tags: []
categories: ["编程语言"]
slug: "8-53"
draft: false
lastmod: "2013-08-16T14:48:29Z"
id: 1924823
url: "https://bingooh.iteye.com/blog/1924823"
---

使用反射（reflection）创建对象，访问方法和属性的缺点包括：

1.不能在编译时进行类型检查

2.反射代码比较繁复

3.性能较低，可能比正常的方法调用低2-50倍

 

如果被反射的类继承了父类或实现了接口，那么可使用接口/父类类型引用此反射类，然后调用相关方法，以下代码通过反射调用ArrayList对象的add()：

```
	@Test
	public void doByReflection() throws Exception{
		Class<?> clazz=Class.forName("java.util.ArrayList");
		 Object list= clazz.newInstance();		
		 Method addMethod=clazz.getMethod("add", Object.class);
			for(int i=0;i<10000;i++)
				addMethod.invoke(list, i);
		
		Integer size=(Integer) clazz.getMethod("size").invoke(list);
		Assert.assertEquals(size, Integer.valueOf(10000));
	}
```

 

以下代码通过List接口调用了ArrayList对象的add()方法（理论上性能更高，实际测试时发现不一定，与前者相比，有时候更慢）：

```
	@Test
	public void doByNormal() throws Exception{
		Class<?> clazz=Class.forName("java.util.ArrayList");
		List<Integer> list=(List<Integer>) clazz.newInstance();
		for(int i=0;i<10000;i++)
			list.add(i);
		
		Assert.assertEquals(list.size(), 10000);
	}
```

 

一般反射用于开发工具或应用工具分析系统所具有的类以及他们所支持的方法。在正常的应用系统里，应尽量避免使用反射创建对象或调用对象方法