[ 登录注册 ]

Java

数组反射机制的应用小例------getComponentType

2016/08/24 13:12 [db:作者] 返回上一页

[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: " + componentClass); 
    } 
 

输出结果:
[html]
ArrayClass:class [I ,----ArrayName: [I,------- Component: int 
ArrayClass:class [Ljava.awt.Button; ,----ArrayName: [Ljava.awt.Button;,------- Component: class java.awt.Button 
ArrayClass:class [[Ljava.lang.String; ,----ArrayName: [[Ljava.lang.String;,------- Component: class [Ljava.lang.String; 
ArrayClass:class [Ljava.lang.String; ,----ArrayName: [Ljava.lang.String;,------- Component: class java.lang.String 
作者:bengda
点击复制链接 与好友分享!回本站首页

文章来源:http://www.bozhiyue.com/java/2016/0824/426399.html
评论
发表评论