class="java"> package 测试; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.Modifier; public class TestDemo { public String toString(Object obj) {//重写toString()方法 Class clazz = obj.getClass(); StringBuilder sb = new StringBuilder(); Package pakName = clazz.getPackage(); sb.append("包名:"+pakName.getName()+"\t"); String className = clazz.getSimpleName(); sb.append("类名:"+className+"\n"); sb.append("公共构造方法:\n"); //获得所有代表构造方法的Constructor数组 Constructor[] cons = clazz.getDeclaredConstructors(); for(Constructor constructor : cons) { String modifier = Modifier.toString(constructor.getModifiers());//获得修饰符 if(modifier.contains("public")) { sb.append(constructor.toGenericString()+"\n"); } } sb.append("公共域:\n"); Field[] fields = clazz.getDeclaredFields();//获得代表所有域的Field数组 for(Field field : fields) { String modifier = Modifier.toString(field.getModifiers()); if(modifier.contains("public")) { sb.append(field.toGenericString()+"\n"); } } sb.append("公共方法:\n"); Method[] methods = clazz.getDeclaredMethods();//获得代表所有方法的Method数组 for(Method method : methods) { String modifier = Modifier.toString(method.getModifiers()); if(modifier.contains("public")) {//查看修饰符是否有public sb.append(method.toGenericString()+"\n"); } } return sb.toString(); } public static void main(String args[]){ System.out.println(new TestDemo().toString(new java.util.Date()));//在此处输入你要反射查询的java类,比如此处查询的是Date()类 } }