什么是反射 反射(Reflection)是java的特征之一。 1 能够在运行时动态检查类自身的类和方法。 2 能够获得java类中各个成员的名称并显示出来。 javaBean是reflection的实际运用之一。 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 // src/HelloWorld.java public static void main(String[] args) { // TODO Auto-generated method stub try { Class c = Class.forName("Javass.c10.HelloWorld"); Method ms[] = c.getDeclaredMethods(); for (Method a : ms) { System.out.println(a.getName()+"->"+a.getReturnType().getName()); } } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } } 二、动态构造一个类,并动态调用其方法 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 public static void main(String[] args) { try { Class c = Class.forName("Javass.c10.HelloWorld"); Class paramtype[] = new Class[2]; paramtype[0] = Integer.TYPE;//int paramtype[1] = String.class; Constructor cs = c.getConstructor(paramtype); Object param[] = new Object[2]; param[0] = 100; param[1] = "sunquan"; //dynamic create one Class……

阅读全文