package com.liuyanzuo;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.HashMap;
import java.util.HashSet;
public class Reflect_1 {
/*
* 反射的基本使用
*
*/
public static void main(String[] args) {
String s=new String();
HashMap hm=new HashMap();
Reflect_1.show(hm);
}
public static void show(Object p){
//打印class的头信息
System.out.print(Modifier.toString(p.getClass().getModifiers())+" class "+p.getClass().getSimpleName()+" ");
//获得父类的信息,默认Object不写
String superClassName=Reflect_1.getSuperClass(p);
if(!superClassName.equals("")){
System.out.println("extends "+Reflect_1.getSuperClass(p));
}
//获得接口的信息
String inter=Reflect_1.getInterfaces(p);
if(!inter.equals("")){
System.out.println("implements"+inter+"{");
}
//获得构造方法的信息
String constructors=Reflect_1.getConstructors(p);
if(!constructors.equals("")){
System.out.println(" "+constructors);
}
//获得属性的信息
String field=Reflect_1.getFields(p);
if(!field.equals(""))
System.out.println(" "+field);
//获得方法的信息
String methods=Reflect_1.getMethods(p);
if(!methods.equals(""))
System.out.println(" "+methods);
System.out.println("}");
}
public static String getConstructors(Object o){
String re="";
Constructor<?>[] cons=o.getClass().getConstructors();
for(Constructor c:cons){
Class<?> [] params=c.getParameterTypes();
//获得参数的SimpleName
String temp=c.getName();
int last=temp.lastIndexOf(".");
temp=temp.substring(last+1, temp.length());
//构成语句,依次:构造方法的Modifier类型(public、private等等)+构造方法名字+(参数)
re=re+Modifier.toString(c.getModifiers())+" "+temp+"(";
if(params.length!=0){
for(int i=0;i<params.length;i++){
re=re+params[i].getSimpleName()+" arg"+i;
if(i<params.length-1)
re=re+",";
}
}
re=re+"){}\r\n ";
}
return re;
}
public static String getSuperClass(Object o){
String re="";
re=o.getClass().getSuperclass().getSimpleName();
if(re.equals("Object"))
return "";
return re;
}
public static String getInterfaces(Object o){
String re="";
Class<?>[] interfaces=o.getClass().getInterfaces();
if(interfaces.length!=0)
{
for(int i=0;i<interfaces.length;i++){
re=re+" "+interfaces[i].getSimpleName();
if(i<interfaces.length-1)
re=re+",";
}
}
return re;
}
public static String getFields(Object o){
String re="";
Field [] fds=o.getClass().getDeclaredFields();
for(Field f:fds){
re=re+Modifier.toString(f.getModifiers())+" "+f.getType().getSimpleName()+" "+f.getName()+";\r\n ";
}
return re;
}
public static String getMethods(Object o){
String re="";
Method [] methods=o.getClass().getDeclaredMethods();
for(Method m:methods){
re=re+Modifier.toString(m.getModifiers())+" "+m.getReturnType().getSimpleName()+" "+m.getName()+"(";
Class<?>[] params=m.getParameterTypes();
for(int i=0;i<params.length;i++){
re=re+params[i].getSimpleName()+" arg"+i;
if(i<params.length-1)
re=re+",";
}
re=re+"){}\r\n ";
}
return re;
}
}
1