---
title: "Java的反射机制中通过Class类的getComponentType()方法"
author: "413899327"
date: "2010-08-25T16:59:18Z"
tags: []
categories: ["编程语言"]
slug: "java-class-getcomponenttype"
draft: false
lastmod: "2010-08-25T17:00:03Z"
id: 747023
url: "https://rogerfederer.iteye.com/blog/747023"
---

Java的反射机制中通过Class类的getComponentType()方法可以取得一个数组的Class对象，那么什么是“数组的Class对象”？


所有的JAVA类都继承自object,那数组也不例外。就是说一个数组本身就是一个class,你得到这个数组的CLASS对象后，可以把它转型为数组。


```java
package Ref;

import java.awt.Button;

public class SampleComponentReflection {

	public static void main(String[] args) {
		int[] ints = new int[2];
		Button[] buttons = new Button[6];
		String[][] twoDim = new String[4][5];
		String[] two = new String[4];

		printComponentType(ints);
		printComponentType(buttons);
		printComponentType(twoDim);
		printComponentType(two);
	}

	static void printComponentType(Object array) {
		Class arrayClass = array.getClass();
		String arrayName = arrayClass.getName();
		Class componentClass = arrayClass.getComponentType();
		String componentName = componentClass.getName();
		System.out.println("ArrayClass:"+arrayClass+" ,----ArrayName: " + arrayName + ",------- Component: "
				+ componentName);
	}

}
```


结果：

ArrayClass:class