import java.lang.reflect.*;
public class ReflectUtil {
public static void reflect(String cName){
try{
Class c=Class.forName(cName);
Class superc=c.getSuperclass();
System.out.print("class "+c.getName());
if(superc!=null&&superc!=Object.class)
System.out.print(" extends"+superc.getName());
System.out.print("\n{\n");
printConstructors(c);
System.out.println();
printMethods(c);
System.out.println();
printFields(c);
System.out.println("}");
}catch(ClassNotFoundException e){
e.printStackTrace();
}
System.exit(0);
}
private static void printConstructors(Class cl)
{
Constructor[] constructors=cl.getDeclaredConstructors();
for(Constructor c:constructors)
{
String name=c.getName();
System.out.print(" "+Modifier.toString(c.getModifiers()));
System.out.print(" "+name+"(");
Class[] paramTypes=c.getParameterTypes();
for(int j=0;j<paramTypes.length;j++)
{
if(j>0) System.out.print(",");
System.out.print(paramTypes[j].getName());
}
System.out.println(");");
}
}
private static void printMethods(Class cl)
{
Method[] methods=cl.getDeclaredMethods();
for(Method m:methods)
{
Class retType=m.getReturnType();
String name=m.getName();
System.out.print(" "+Modifier.toString(m.getModifiers()));
System.out.print(" "+retType.getName()+" "+name+"(");
Class[] paramTypes=m.getParameterTypes();
for(int j=0;j<paramTypes.length;j++)
{
if(j>0) System.out.print(",");
System.out.print(paramTypes[j].getName());
}
System.out.println(");");
}
}
private static void printFields(Class c)
{
Field[] fields=c.getDeclaredFields();
for(Field f:fields)
{
Class type=f.getType();
String name=f.getName();
System.out.print(" "+Modifier.toString(f.getModifiers()));
System.out.println(" "+type.getName()+" "+name+";");
}
}
}
class InnerVistOuterPrivate
{
public static void main(String[] args)
{
System.out.println("Hello World!");
new Outer().new Inner().print();
}
}
//代码2:外部类对内部类可见
//(内部类可以访问外部类的所有成员变量和方法)
class Outer{
//外部类私有数据域
private int data=100;
//内部类
class Inner{
void print(){
//内部类访问外部私有数据域
System.out.println(data);
}
}
}
/*
Hello World!
100
请按任意键继续. . .
*/
class RefOuterInner
{
public static void main(String[] args)
{
ReflectUtil.reflect("Outer$Inner") ;
}
}
/*
class Outer$Inner
{
Outer$Inner(Outer);
void print();
final Outer this$0;
}
请按任意键继续. . .
*/