JavaSE教程_进阶

全部教程

×

Java反射类的信息

package com.wkcto.chapter08.demo01;

import java.lang.reflect.Modifier;

/**
 * 通过反射技术, 反射类的信息
 * @author 蛙课网
 *
 */
public class Test02 {

	public static void main(String[] args) {
		//1)创建Class对象
//		Class<?> class1 = String.class;
		Class<?> class1 = Integer.class;
		
		//2)反射类的信息
		//2.1 类的修饰符
		int mod = class1.getModifiers();
		String modifiers = Modifier.toString(mod);
		System.out.print( modifiers );
		
		//2.2 类名
		System.out.print(" class ");
//		System.out.print( class1.getName() ); 		//完整类名 
		System.out.print( class1.getSimpleName() ); //简易类名
		
		//2.3父类
		Class<?> superclass = class1.getSuperclass();
		//如果父类是Object,不显示父类
		if ( Object.class != superclass) {
			System.out.print(" extends ");
			System.out.println( superclass.getSimpleName() );			
		}
		//2.4接口
		Class<?>[] interfaces = class1.getInterfaces();
		if ( interfaces.length > 0 ) {
			System.out.print(" implements ");
			//遍历接口数组
			for (int i = 0; i < interfaces.length; i++) {
				System.out.print( interfaces[i].getSimpleName() );
				//接口名之间使用逗号分隔
				if ( i != interfaces.length - 1) {
					System.out.print(",");
				}
			}
		}
		
	}

}

 

技术文档推荐

更多>>

视频教程推荐

更多>>