java利用反射獲取類資訊
阿新 • • 發佈:2018-12-26
在java.lang.reflect包中有三個類Field、Monthod和Constructor分別描述類的域、方法和構造器。還可以使用java.lang.reflect包中的Modifier類的靜態方法分析getModifiers返回的整型數值。例如可以使用ispublic、isprivate、isFinal 判斷方法是否是public、private、final。另外還可以使用Modifier.toString方法將修飾符打印出來
下列程式通過使用者輸入的有效類列印類的全部資訊
package com.concurrent; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.Scanner; /** * <br/>功能: * <br/>作者:lixin51 * <br/>建立日期:2016/11/16 */ public class ReflectionTest { public static void main(String[] args){ String name; if (args.length>0) { name = args[0]; }else { Scanner in = new Scanner(System.in); System.out.println("Enter Class name"); name = in.next(); } try { Class c1 = Class.forName(name); //返回此Class所表示的實體的超類Class Class super1 = c1.getSuperclass(); //獲取該類的修飾符 String modifiers = Modifier.toString(c1.getModifiers()); if (modifiers.length()>0) System.out.print(modifiers+" "); if (super1 != null && super1 != Object.class) System.out.print("extends "+super1.getName()); printContructors(c1); printMethods(c1); printFields(c1); } catch (ClassNotFoundException e) { e.printStackTrace(); } System.exit(0); } /** * 獲取構造器資訊 * @param cl */ public static void printContructors(Class cl){ Constructor[] constructors = cl.getDeclaredConstructors(); for (Constructor c: constructors){ //獲取方法名 String name = c.getName(); System.out.print(" "); //獲取建構函式的修飾符 String modifiers = Modifier.toString(c.getModifiers()); if(modifiers.length()>0){ System.out.print(modifiers+" "); } System.out.print(name+"("); //獲取建構函式的引數 Class[] paramTypes = c.getParameterTypes(); for (int j=0;j<paramTypes.length;j++){ if (j>0) System.out.print(paramTypes[j].getName()); } System.out.println(");"); } } /** * 獲取類中的方法 * @param c1 */ public static void printMethods(Class c1){ Method[] methods = c1.getDeclaredMethods(); for (Method m : methods) { Class retType = m.getReturnType(); String name = m.getName(); System.out.print(" "); //列印訪問修飾符 返回型別 、方法名稱 String modifiers = Modifier.toString(m.getModifiers()); if (modifiers.length()>0){ System.out.print(modifiers+" "); } System.out.print(retType.getName()+" "+name+"("); //列印方法中的引數 Class[] paramTypes = m.getParameterTypes(); for (int j=0;j<paramTypes.length;j++){ if(j>0) System.out.print(paramTypes[j].getName()); } System.out.println(");"); } } /** * 獲取類中的域 * @param c1 */ public static void printFields(Class c1){ Field[] fields = c1.getDeclaredFields(); for (Field f : fields){ Class type = f.getType(); String name = f.getName(); System.out.print(" "); String modifiers = Modifier.toString(f.getModifiers()); if(modifiers.length()>0){ System.out.print(modifiers+" "); } System.out.println(type.getName()+" "+name+";"); } } }