package test.my.chap0302;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.Date;
public class StringUtils {
@SuppressWarnings("unchecked")
public String toString(Object obj){
StringBuilder sb = new StringBuilder();
Class cs = obj.getClass();//获取该类的class对象
String clasName = cs.getSimpleName(); //获取该类的类名
Package packageName = cs.getPackage(); //包名
sb.append("包名是:"+packageName+"\n");
sb.append("类名是:"+clasName+"\n");
Constructor[] cons = cs.getDeclaredConstructors(); //所有构造器
for(Constructor con:cons){
String modifer = Modifier.toString(con.getModifiers());
if(modifer.contains("public")){
sb.append("构造器:"+con.toGenericString()+"\n");
}
}
Method[] ms = cs.getDeclaredMethods(); //所有方法
for(Method md:ms){
String modifer = Modifier.toString(md.getModifiers());
if(modifer.contains("public")){
sb.append("方法:"+md.toGenericString()+"\n");
}
}
Field[] fields = cs.getDeclaredFields();
for(Field f:fields){
String modifier = Modifier.toString(f.getModifiers());
if(modifier.contains("public")){
sb.append("公共字段:"+f.toGenericString()+"\n");
}
}
return sb.toString();
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println(new StringUtils().toString(new Date()));
}
}