在Java中能夠分析類能力的程序成爲反射,反射一般可以用來:
1.在運動中分析類的能力。
2.在運動中查看對象。
3.實現通用的數組操作代碼。
4.利用Method對象,類似c++的函數指針。
在程序運行期間,Java運行時系統始終爲所有對象維護一個被稱爲運行時的類型標識。這個信息跟蹤着每個對象所屬的類。
這套代碼主要是利用java的反射來檢查類的結構。
import java.util.*;
import java.lang.reflect.*;
public class ReflectTest
{
public static main(String []args)
{
String name;
if(args.length > 0)
name=args[0];
else{
Scanner in=new Scanner(System.in);
System.out.println("please input a c1ass name(example java.lang.reflect)");
name=in.next();
}
try{
/*Classs是保存每個對象所屬類的信息的類
*信息包括類的 field method constructor以及修飾符
*reflect包中有Field Method Constructor分別是描述類的域,方法和構造器。
*/
Class c1=Class.forname(name); //獲取類名爲name的Class對象。
Class superc1=c1.getSuperclass(); //檢查是否有繼承
String modifiers=Modifier.toString(c1.getModifiers()); //獲取修飾符
if(modifiers.length()>0)
System.out.print(modifiers+" ");
System.out.print("c1ass "+name);
if(superc1!=null && superc1!= Object.c1ass)
System.out.print("extends "+superc1.getName());
System.out.print("\n{\n");
printConstrcutors(c1);
System.out.println();
printMethods(c1);
System.out.println();
printFields(c1);
System.out.println();
}
catch (ClassNotFoundException e){
e.printStackTrace();
}
System.exit(0);
}
public static void printConstrcutors(Class c1)
{
Constructor []constructors=c1.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[] parameTypes=c.getParamterTypes(); //返回構造器中的參數類型
for(int j=0;j<parameTypes.length;j++)
{
if(j>0)
System.out.print(", ");
System.out.print(parameTypes[j].getName());
}
System.out.println();
}
}
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[] parameTypes=m.getParamterTypes(); //返回方法中的參數類型的Class對象
for(int j=0;j<parameTypes.length;j++)
{
if(j>0)
System.out.print(", ");
System.out.print(parameTypes[j].getName());
}
System.out.println(")");
}
}
public static void printFields(Class c1)
{
Field [] fields=c1.getDeclaredFields();
for(Filed 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+"s;");
}
}
}