Java反射的几个小实例
//显示父类和所有接口 public static void showSuperclassAndInterface(String className){ try { Class<?> clazz=Class.forName(className); System.out.println(className+"的父类是:\n"+clazz.getSuperclass().getName()); System.out.println("\n"+className+"所包含的接口有:"); Class<?>[] interfaces=clazz.getInterfaces(); for(Class<?> i:interfaces){ System.out.println(i.getName()); } } catch (ClassNotFoundException e) { e.printStackTrace(); } } //显示此类中所有set方法 public static Method[] showSetMethod(String className){ List<Method> list=new ArrayList<Method>(); try { Class<?> clazz = Class.forName(className); Method[] methods=clazz.getMethods(); for(Method m:methods){ if(m.getName().indexOf("set")==0){ list.add(m); } } } catch (ClassNotFoundException e) { e.printStackTrace(); } return list.toArray(new Method[list.size()]); } //显示所有属性的值 public static void showAllPropertyValue(Object bean){ Class<?> clazz=bean.getClass(); Method[] methods=clazz.getMethods(); List<Method> list=new ArrayList<Method>(); for(Method m:methods){ if(m.getName().indexOf("get")==0){ list.add(m); } } for(Method m:list){ try { System.out.println(m.getName().substring(3)+"屬性的值是:"+m.invoke(bean, null)); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } } } public static void main(String[] args) { //showSuperclassAndInterface("java.util.ArrayList"); /*for(Method m : showSetMethod("Student")){ System.out.println(m.getName()); }*/ Student student=new Student(); student.setName("張三"); student.setAge(22); showAllPropertyValue(student);